Google Analytics(分析)应该放在HTML页面的头部还是底部? [英] Should Google Analytics go in the head or bottom of an HTML page?

查看:157
本文介绍了Google Analytics(分析)应该放在HTML页面的头部还是底部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Google建议在关闭< / head> 之前放置google analytics脚本。

我宁愿将它与剩下的JavaScript结合起来,它们现在都集中在一个缓存的外部文件中,该文件加载在我的HTML文件的底部。我可以按照我的方式行事吗?如果是这样,那么我冒着什么风险/将下面的代码放在头部但是在HTML底部的代价是多少?

 < script type =text / javascript> 
var _gaq = _gaq || [];
_gaq.push(['_ setAccount','UA-22180365-1']);
_gaq.push(['_ setDomainName','none']);
_gaq.push(['_ setAllowLinker',true]);
_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);
})();
< / script>


解决方案

< script> 标签放置在< body> 的末尾是可取的,因为 执行它附带的Javascript时的本质。由于用于GA的Javascript是动态插入的,因此是非阻塞的,您可以将它放在任何地方。



我猜Google唯一看到的问题是,在您网站的底部,您可能无法赶上访问者/页面加载完成前取消请求。如果有人打电话给您的HTML文档并取消请求,那么可能不会遇到GA代码(因此不会执行)。


Google advises putting the google analytics script right before closing the </head>.

However, I would prefer to combine it with the rest my javascript that are now all together in a cached, external file, which is loaded at the bottom of my HTML file. Can I do it my way? If so, what am I risking then/what's the cost of putting the below code not in the head but at the bottom of the HTML?

<script type="text/javascript">
 var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-22180365-1']);
  _gaq.push(['_setDomainName', 'none']);
  _gaq.push(['_setAllowLinker', true]);
  _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);
  })();
</script>

解决方案

You're risking nothing really. Putting <script> tags at the end of the <body> is recommendable because of the blocking nature while executing the Javascript it encloses. Since the Javascript for GA is dynamically inserted and therefore non-blocking, you can put it anywhere.

I guess the only "problem" Google sees is, when putting that code at the bottom of your site, you might not catch visitors / pageloads cancel the request before completed. If someone calls your HTML document and cancels the request, the GA code might not get encountered (and therefore, not executed).

这篇关于Google Analytics(分析)应该放在HTML页面的头部还是底部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆