javascript - 检测Google Analytics是否已加载? [英] javascript - Detect if Google Analytics is loaded yet?

查看:93
本文介绍了javascript - 检测Google Analytics是否已加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个项目,该项目将在Google Analytics自定义变量中存储一些信息。我正在构建的脚本需要检测GA是否已加载,然后才能将数据推送到该脚本。该项目旨在跨任何使用GA的网站进行工作。问题是可靠地检测GA是否已完成加载并可用。



这里有几个变化:


  1. 加载GA有多种方法。从Urchin时代开始的旧版脚本到最新的异步脚本。其中一些是内联的,一些是异步的。此外,有些网站会自动加载GA,就像我的工作一样。我们使用YUI getScript来加载它。


  2. 变量名称。在某些脚本中,分配给GA的变量名称是 pageTracker 。在其他情况下,它的 _gaq 。然后,网站可能会使用自定义变量名称来实现GA。


关于什么可能是一种可靠的方法来检查Google Analytics是否在页面上使用,以及它是否已被加载的任何想法?

解决方案

 函数checkIfAnalyticsLoaded(){
if(window._gaq&& window._gaq._getTracker){
//跟踪新样式分析
} else if(window.urchinTracker){
//使用旧式分析
跟踪} else {
//重试。可能希望限制您呼叫此次的总次数。
setTimeout(500,checkIfAnalyticsLoaded());
}
}


I'm working on a project here that will store some info in Google Analytics custom variables. The script I'm building out needs to detect if GA has loaded yet before I can push data to it. The project is being designed to work across any kind of site that uses GA. The problem is reliably detecting if GA has finished loading or not and is available.

A couple of variabilities here:

  1. There's multiple methods of loading GA. Older scripts from the Urchin days up to the latest asynchronous scripts. Some of these are inline, some are asynchronous. Also, some sites do custom methods of loading GA, like at my job. We use YUI getScript to load it.

  2. Variable-variable names. In some scripts, the variable name assigned to GA is pageTracker. In others, its _gaq. Then there's the infinity of custom variable names that sites could be using for their implementation of GA.

So does anyone have any thoughts on what might be a reliable way to check if Google Analytics is being used on the page, and if it's been loaded?

解决方案

function checkIfAnalyticsLoaded() {
  if (window._gaq && window._gaq._getTracker) {
    // Do tracking with new-style analytics
  } else if (window.urchinTracker) {
    // Do tracking with old-style analytics
  } else {
    // Retry. Probably want to cap the total number of times you call this.
    setTimeout(500, checkIfAnalyticsLoaded());
  }
}

这篇关于javascript - 检测Google Analytics是否已加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆