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

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

问题描述

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

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.

这里有几个变量:

  1. 有多种加载 GA 的方法.从 Urchin 时代到最新的异步脚本的旧脚本.其中一些是内联的,一些是异步的.此外,一些站点会自定义加载 GA 的方法,例如在我的工作中.我们使用 YUI getScript 来加载它.

  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.

变量-变量名.在某些脚本中,分配给 GA 的变量名称是 pageTracker.在其他情况下,它的 _gaq.还有无数的自定义变量名称可供网站用于其 GA 实施.

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.

那么对于检查页面上是否使用了 Google Analytics 以及它是否已加载的可靠方法,有没有人有任何想法?

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(checkIfAnalyticsLoaded, 500);
  }
}

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

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