Google Analytics(分析)应该放在HTML页面的头部还是底部? [英] Should Google Analytics go in the head or bottom of an HTML page?
问题描述
Google建议在关闭< / head>
之前放置google analytics脚本。
< 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屋!