Javascript 通过引用将Google Analytics对象传递给函数的问题
为了跟踪一些ajax事件,我为我的javascript制作了一个助手,下面是设置的简短版本Javascript 通过引用将Google Analytics对象传递给函数的问题,javascript,arrays,object,google-analytics,pass-by-reference,Javascript,Arrays,Object,Google Analytics,Pass By Reference,为了跟踪一些ajax事件,我为我的javascript制作了一个助手,下面是设置的简短版本 analytics:{ active: false, gaq: null, init: function(gaq){ this.active = true; this.gaq = gaq; $('a[href^=\"http://\"]').live('click', function
analytics:{
active: false,
gaq: null,
init: function(gaq){
this.active = true;
this.gaq = gaq;
$('a[href^=\"http://\"]').live('click', function() {
helper.analytics.trackPageview('/outgoing/' + $(this).attr('href'));
return true;
});
},
trackPageview: function(page){
if(this.active === false){
return;
}
this.gaq.push(['_trackPageview',page]);
}
},
我有通用的谷歌分析设置
<script type="text/javascript">
var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-xxxxxxxx-1']);
_gaq.push(['_setDomainName', '.example.com']);
_gaq.push(['_trackPageview']);
(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);
})();
$(document).ready( function() {
helper.analytics.init(_gaq);
});
</script>
var _gaq=_gaq | |[]_gaq.push([''设置帐户','UA-xxxxxxxx-1']);
_gaq.push([''u setDomainName','.example.com']);
_gaq.push([''u trackPageview']);
(功能(){
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);
})();
$(文档).ready(函数(){
helper.analytics.init(_gaq);
});
但是,在控制台中,日志记录会产生一个对象。日志记录helper.analytics.gaq
会生成一个数组,其中附加了新的页面视图,但google analytics不会跟踪该页面视图。为什么没有通过引用将_gaq传递给助手?您在Crome开发工具控制台或Firefox&firebug中看到任何语法错误吗
在初始脚本标记之后有一个
。“
。在创建脚本标记时,ga代码段将async
属性设置为true。因此,它将独立于主体进行加载。您需要将事件处理程序绑定到ga脚本标记的onload事件。类似于:
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.onload = function(){
herlper.analytics.init(_gaq);
};
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);
})();
我还没有测试过这个,但我认为它可能会工作。没有错误,很抱歉,“.”与php sprintf相关,用于填充我的参数。没有语法错误,我可以访问_gaq和helper.analytics.gaq,但我希望两者都是相同的对象,但是helper中的一个是数组