我最近注意到Google分析现在建议在< / head>之前添加其Javascript代码段.标签.他们过去建议在< / body>之前包含代码段.标签.
YUI Best Practices for Speeding Up Your Web Site建议尽可能将脚本放在页面下方,因为脚本可以阻止并行下载:
The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames,you can get more than two downloads to occur in parallel. While a script is downloading,however,the browser won’t start any other downloads,even on different hostnames.
谷歌说:
One of the main advantages of the asynchronous snippet is that you can position it at the top of the HTML document. This increases the likelihood that the tracking beacon will be sent before the user leaves the page. It is customary to place JavaScript code in the
<head>
section,and we recommend placing the snippet at the bottom of the<head>
section for best performance.
我通常更关心用户体验和页面加载速度,而不是确保发送每个跟踪信标,因此这将促使我将Google分析脚本包含在页面底部,而不是在< head>中.,对?
我敢肯定,除了这两种观点外,还有更多的事情需要考虑.影响你的是什么?有什么需要考虑的事情?
那么,让你的脚本正确的优点和缺点是什么?< / head>与之前的对比< / body>?
解决方法
(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); })();