javascript - 检测 Google Analytics 是否已加载?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1954910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript - Detect if Google Analytics is loaded yet?
提问by Geuis
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.
我正在这里开展一个项目,该项目将在 Google Analytics 自定义变量中存储一些信息。我正在构建的脚本需要先检测 GA 是否已加载,然后才能向其推送数据。该项目旨在在任何使用 GA 的站点上工作。问题是可靠地检测 GA 是否已完成加载并可用。
A couple of variabilities here:
这里有几个变量:
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.
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.
有多种加载 GA 的方法。从 Urchin 时代到最新的异步脚本的旧脚本。其中一些是内联的,一些是异步的。此外,某些站点会自定义加载 GA 的方法,例如在我的工作中。我们使用 YUI getScript 来加载它。
变量-变量名。在某些脚本中,分配给 GA 的变量名称是
pageTracker. 在其他情况下,其_gaq. 然后是无数的自定义变量名称,站点可以使用它们来实现 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?
那么有没有人对检查页面上是否使用 Google Analytics 以及是否已加载的可靠方法有任何想法?
采纳答案by Annie
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);
}
}
回答by l2aelba
This, you can put the code above/beforethe Google Analytics Tracking Code:
这一点,你可以把代码上方/前的谷歌Analytics跟踪代码:
function check_ga() {
if (typeof ga === 'function') {
console.log('Loaded :'+ ga);
} else {
console.log('Not loaded');
setTimeout(check_ga,500);
}
}
check_ga();
Demo:http://jsbin.com/rijiyojume/edit?html,console
演示:http : //jsbin.com/rijiyojume/edit?html,console
Or If you can run script afterthe Google Analytics Tracking Code:
或者,如果您可以在Google Analytics 跟踪代码之后运行脚本:
ga(function(tracker) {
console.log(tracker.get('clientId'));
});
Demo:http://jsbin.com/wiqategifo/1/edit?html,console
演示:http : //jsbin.com/wiqategifo/1/edit?html,console
Ref:#ready-callback
回答by soutarm
I'm too lowly to respond to Annie's answer which works but has syntax errors. Analytics names have underscore first and the setTimeout() syntax was backwards (and incomplete). It should be this:
我太卑微了,无法回应安妮的答案,该答案有效但存在语法错误。分析名称先有下划线,而 setTimeout() 语法向后(且不完整)。应该是这样的:
function checkIfAnalyticsLoaded() {
if (window._gat && window._gat._getTracker) {
// Do tracking with new-style analytics
} else if (window.urchinTracker) {
// Do tracking with old-style analytics
} else {
// Probably want to cap the total number of times you call this.
setTimeout(checkIfAnalyticsLoaded, 500);
}
}
回答by Vadim Eremeev
Here is how I did it:
这是我如何做到的:
var ga = window[window['GoogleAnalyticsObject'] || 'ga'];
if (typeof ga == 'function') {
// call ga object here
ga('send', 'event', 'Social Share Button', 'click', 'facebook');
}
回答by AyexeM
None of the above methods worked well for me. Maybe because I am loading GA through GTM, not sure. But this simple method did work from the console for me :
以上方法都不适合我。也许是因为我正在通过 GTM 加载 GA,不确定。但是这个简单的方法对我来说确实可以从控制台运行:
ga.loaded
If you are trying to check from within your script, you may need to wait a bit as GA is loaded after doc ready :
如果您尝试从脚本中进行检查,您可能需要稍等片刻,因为 GA 在 doc ready 后加载:
var t = setTimeout(function(){
console.log(ga.loaded);
}, 999);
回答by oboshto
ECMA2015 style
ECMA2015风格
let checkIfAnalyticsLoaded = () => {
return new Promise((resolve, reject) => {
let timeStart = Date.now();
const TIMEOUT = 3000;
let _isLoaded = function() {
if (Date.now() - timeStart > TIMEOUT) {
reject('Timeout. Google analytics not injected!');
return;
}
if (window.ga && ga.create) {
resolve(ga);
return;
} else {
setTimeout(_isLoaded, 500);
}
};
_isLoaded();
});
}
checkIfAnalyticsLoaded()
.then((result => {
console.log('LOADED', result);
}))
.catch(console.error);
回答by DdW
Adjusted version to wait for Google Analytics to not only have finished loading, but als have generated the clientId (in case you need it, like I do). Also added a cap on amount of retries (20).
调整后的版本以等待 Google Analytics 不仅完成加载,而且还生成了 clientId(以防您需要它,就像我一样)。还增加了重试次数上限 (20)。
var retryCounter = 0;
function checkIfAnalyticsLoaded() {
if ((typeof ga === 'function' && ga.loaded) || retryCounter++ > 20) {
// ga() puts your method in the Command Queue,
// which is applied after GA is done with initialization
ga(yourFunctionHere());
} else {
// Retry.
setTimeout(checkIfAnalyticsLoaded, 500);
}
}
// Auto load
(function () {
checkIfAnalyticsLoaded();
})();
回答by John Lindsey
I'm using this, but I built a helper function out of it that lets me pass in a function and arguments, and they're called when Google Analytics is loaded. It checks once every half second, and stops checking after a minute if Google Analytics hasn't loaded. I thought this might be helpful for others.
我正在使用它,但我从中构建了一个辅助函数,它允许我传入一个函数和参数,并在加载 Google Analytics 时调用它们。它每半秒检查一次,并在一分钟后停止检查是否未加载 Google Analytics。我认为这可能对其他人有帮助。
Usage:
用法:
function add(a,b){alert(a + ' + ' + b + ' = ' + (a+b));}
_mygaq(add,1,2);
Code:
代码:
function _mygaq(fn) {
this._count = this._count || 0;
this._running = this._running || false;
this._q = this._q || [];
if(arguments.length>0){
this._q.push({"f":fn,"p":Array.prototype.slice.call(arguments,1)});
} else {
this._count++;
}
if ((window._gat && window._gat._getTracker) || window.urchinTracker) {
this._count = 0;
this._running = false;
while (this._q.length > 0){
var _innr = this._q[0];
this._q = this._q.slice(1);
_innr.f.apply(_innr.f, _innr.p);
}
} else {
if( (arguments.length==0) || (!this._running && arguments.length>0)){
if(this._count < 120) setTimeout('_mygaq()', 500);
this._running = true;
}
}
}
回答by Robert Waddell
I have a different solution for this if anyone cares to try it out. This assumes your Google Analytics Object is 'ga'. Change your timeout and max tries to suit your application.
如果有人愿意尝试,我对此有不同的解决方案。这假设您的 Google Analytics 对象是“ga”。更改您的超时和最大尝试以适合您的应用程序。
<script type="text/javascript">
var counter = 1;
function checkIfAnalyticsLoaded() {
if (window.ga) {
//LOADED!
} else {
counter = counter + 1;
if (counter < 6){
setTimeout('checkIfAnalyticsLoaded()', 200);
} else {
//LOADED!
}
}
}
window.onload = checkIfAnalyticsLoaded();
</script>
回答by Carter Cole
you may also look into the new Asynchronous Trackingand then you wont need to check you can just do whatever and it will send the data as soon as it loads...
您还可以查看新的异步跟踪,然后您无需检查您可以做任何事情,它会在加载后立即发送数据...

