2013-07-19 31 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>被设置之前被调用,并且我以其他方式获得空白的标题。

相关问题