2012-07-16 44 views
0

使用Google Analytics(分析)实施自定义解决方案来跟踪网页,活动和其他内容我想检查ga.js图书馆是否已包含在内以避免双重包含,因为我在一个拥有多个利益相关者的环境也可以使用Google Analytics,并且重叠是一种可能性。检查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'); 
    } 
} 

它的工作原理,并记录多个包括潜在的错误。 后来我想的东西更聪明,通过检查_gaq栈的对象原型:

with (window) { 
    if (_gaq instanceof Array) { 
     // not loaded, so include it... 
    } else { 
     // it's been included 
    } 
} 

_gaq对象仍然由ga.js库未初始化,这是一个简单的数组,所以第一个条件是真实的。 初始化时,它会被覆盖为一个对象,而不再是Array基本对象的实例。

缺点

我想知道有关window.onload史诗问题:实施解决方案,同步码(在它所处的点计算),如果ga.js库已被列入,但尚未加载到DOM因为异步调用,无论如何会产生双重包含。 因此,应该触发DOMContentLoaded事件来调用这两个解决方案中的一个。

我在网上搜索了围绕这个主题的类似问题,但官方的GA文档缺乏有关它的信息,对热门资源的结果似乎都没有对待它。

我给我提出的另一个问题是双重包含是一个问题:从纯粹的技术角度来看,我认为Google Analytics可以预测这类用户错误并对其进行管理,因为在某些情况下它确实(有人知道如果是这样?)。但从用户的角度来看,第二次无用HTTP请求的时间很烦人,希望能够避免。

有人遇到这个问题或有一些建议吗?

回答