Avoid create the ga.js duplicate.
js file googletracker.js
function startTrace(){
(function() {
var scripts= document.getElementsByTagName('script');
var path= scripts[0].src.split("/")[3];
if(path != "ga.js"){
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);
}else{
s = document.getElementsByTagName('script')[0]; s.remove();
s = document.getElementsByTagName('script')[0];//get script[0] again
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';
s.parentNode.insertBefore(ga, s);
}
})();
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-xxxxxxx-x']);
_gaq.push(['_trackPageview']);
alert('inside function: ' + document.title);
}
In the templat page add
<af:resource source="/googletracker.js" type="javascript"/>
<af:resource type="javascript">
startTrace();
</af:resource>
本文介绍了一种在网页中防止谷歌分析脚本ga.js重复加载的方法。通过检查当前页面是否已加载ga.js来决定是否再次加载,确保了谷歌跟踪代码只被加载一次,避免了资源浪费和可能产生的错误。
6万+

被折叠的 条评论
为什么被折叠?



