2013-07-19 34 views
0

我想找到一種方法來從document.ready()函數添加谷歌分析代碼。以下代碼不起作用。來自jQuery的document.ready()的谷歌分析不起作用

$(document).ready(function() { 
      var _gaq = window._gaq || []; 
       _gaq.push(['e._setAccount', 'UA-XXXZZ-1']); 
       _gaq.push(['e._setDomainName', 'company.com']); 
       _gaq.push(['e._trackPageview']); 
       _gaq.push(['a._setAccount', 'UA-XXXYY-1']); 
       _gaq.push(['a._setDomainName', 'company.com']); 
       _gaq.push(['a._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); 
       })();  
}); 

解決方案是什麼?我可以把創建鏈接到ga.js文件的代碼片段放在head標籤中,但它能解決問題嗎?

由於

+1

爲什麼要將它添加到document.ready函數中?只需將其粘貼到頁面上的腳本塊中即可完成工作! –

+0

谷歌分析具有特定的安裝說明。如果你遵循它們,它的作品。沒有必要將代碼放在'$ document.ready()' – 2013-07-19 08:35:55

+0

我想用Google analytics進行A-B內容測試,並且A-B測試腳本必須在GA腳本之前觸發。但是,由於CMS限制,所有頁面特定的腳本都放置在站點範圍的腳本(即GA代碼)之後。所以我需要找到一種方法來在加載頭標籤中的所有其他腳本之後運行GA代碼。 – lekso

回答

0

刪除$(文件)。就緒(函數(){

和記錄準備結束標記=>});

因爲谷歌分析不端的文件準備功能工作

+0

你能解釋爲什麼它不會或提供一個鏈接,這是解釋? – lekso

+0

從谷歌 https://support.google.com/analytics/answer/1008080?hl=en 但這個鏈接在你的代碼 $(函數(){............ 。==同$(document).ready 我認爲可以解決:D –

+0

抱歉,兩者都是'no'。你的鏈接只是給出了GA代碼的放置位置,$(function())和document 。ready()做一些不同的事情 – lekso

1

下面的設置似乎很好地工作:在文件準備附加

<script type="text/javascript"> 
    (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); 
    })(); 
</script> 

:在頁面頭部 添加這個腳本,它會立即運行跟蹤代碼:

$(document).ready(function() { 
     var _gaq = window._gaq || []; 
     _gaq.push(['e._setAccount', 'UA-XXXZZ-1']); 
     _gaq.push(['e._setDomainName', 'company.com']); 
     _gaq.push(['e._trackPageview']); 
     _gaq.push(['a._setAccount', 'UA-XXXYY-1']); 
     _gaq.push(['a._setDomainName', 'company.com']); 
     _gaq.push(['a._trackPageview']); }); 
0

Another question答案,它爲您和masadi是在正確的軌道上:

文檔ready函數意味着_gaq變量的範圍太有限。當ga.js中的其他Google腳本運行時,它找不到變量。通過將_gaq填充到全局範圍內(在任何其他功能之外或使用window.gaq),可以找到該變量。

將其放入文檔ready的唯一好處是在分析運行之前確保DOM已完成。對我來說,這是因爲劇本在<title>被設置之前被調用,並且我以其他方式獲得空白的標題。

相關問題