Google analytics 检查是否已经包括谷歌分析库

Google analytics 检查是否已经包括谷歌分析库,google-analytics,loading,inclusion,Google Analytics,Loading,Inclusion,通过Google Analytics实现跟踪页面、事件和其他内容的定制解决方案,我想检查一下ga.js库是否已经被包括在内,以避免双重包括,因为我在一个多个利益相关者也使用Google Analytics的环境中工作,而且重叠是可能的 首先,我想循环所有当前脚本,查找src属性: // load the Google Analytics library only if it has not been already loaded: var gaScripts = 0; // number of

通过Google Analytics实现跟踪页面、事件和其他内容的定制解决方案,我想检查一下
ga.js
库是否已经被包括在内,以避免双重包括,因为我在一个多个利益相关者也使用Google Analytics的环境中工作,而且重叠是可能的

首先,我想循环所有当前脚本,查找
src
属性:

// load the Google Analytics library only if it has not been already loaded:
var gaScripts = 0; // number of ga.js scripts in the current document
var scripts = document.getElementsByTagName('script');

for (var i in scripts) {
    // go through all the scripts:
    if (typeof(scripts[i].src) !== 'undefined' && scripts[i].src.split('?')[0].match(/ga\.js$/)) {
        // update the counter if ga.js has been found:
        gaScripts++;
    }
}

if (gaScripts === 0) {
    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();

    // update the counter:
    gaScripts++;

} else if (gaScripts > 1) {
    // the ga.js library has been loaded more than once, log this error:
    if (window.console) {
        console.log('Warning: the ga.js script has been included ' + gaScripts + ' times in the page');
    }
}
它可以工作,还可以记录多个包含的潜在错误。 然后,通过检查
\u gaq
堆栈的对象原型,我想到了更聪明的方法:

with (window) {
    if (_gaq instanceof Array) {
        // not loaded, so include it...
    } else {
        // it's been included
    }
}
\u gaq
对象仍然未被
ga.js
库初始化时,它是一个简单数组,因此第一个条件为true。 当它被初始化时,它将作为一个对象被覆盖,而不再是数组基元对象的实例

缺点

我想知道
window.onload
epic问题:将解决方案实现为同步代码(在它所在的点上进行评估),如果
ga.js
库已经被包含,但由于异步调用而尚未加载到DOM中,它无论如何都会导致双重包含。 因此,应该触发
DOMContentLoaded
事件,以调用其中的两个解决方案之一

我在网上搜索了关于这个主题的类似问题,但是正式的GA文档缺少关于它的信息,流行资源上的结果似乎都没有处理它

我向我提出的另一个问题是双重包含是否是一个问题:从纯技术的角度来看,我认为谷歌分析可以预测这种用户错误并加以管理,就像在某些情况下一样(有人知道是否如此吗?)。但是从用户的角度来看,第二个无用的HTTP请求的时间很烦人,希望能够避免


是否有人遇到了这个问题或提出了一些建议?

尝试键入ga.js中定义的_gat对象。至于这一切的时间安排和双重包含问题,我认为没有任何功能上的理由不能包含两次。这是额外的开销,但ga.js所做的只是提供一些要调用的函数

使用double include进行尝试,看看GA调试工具是否对此有什么建议: