2012-02-11 103 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