2012-02-11 105 views
0

我为了跟踪一些Ajax事件做了一个帮手我的JavaScript通过谷歌分析对象的功能,这里是它的成立是问题通过参考

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> 

然而在控制台登录_gaq结果中的对象。将helper.analytics.gaq结果记录到一个数组中,并附加新的浏览量,但在Google Analytics(分析)中不会跟踪综合浏览量。
为什么_gaq没有通过引用传递给帮助者?

回答

1

创建脚本标记时,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); 
})(); 

我没有测试过这个,但我认为它可能工作。

+0

伟大的,这解决了它:) – Moak 2012-02-15 09:30:17

0

您是否在Crome开发工具控制台或Firefox & firebug中看到任何语法错误?

在初始脚本标记后面有一个'."

+0

没有错误,抱歉,'。“与php sprintf有关,用于填写我的参数。没有语法错误,我可以访问_gaq和helper.analytics.gaq,但我希望两者都是相同的对象,然而在助手中的人是一个数组 – Moak 2012-02-11 05:14:18