什么是最快的异步谷歌分析片段?

时间:2016-03-12 15:21:24

标签: javascript performance asynchronous google-analytics

我会使用最快的异步谷歌分析片段,但我不是一个优秀的程序员,所以我不知道什么是最好的:

A)

<!-- Google Analytics -->
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
</script>
<script async src='//www.google-analytics.com/analytics.js'></script>
<!-- End Google Analytics -->

https://developers.google.com/analytics/devguides/collection/analyticsjs/tracking-snippet-reference#async-snippet-minified

B)

<script>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script');
ga.src = ('https:' == document.location.protocol ? 'https://ssl' :   'http://www') + '.google-analytics.com/ga.js';
ga.setAttribute('async', 'true');
document.documentElement.firstChild.appendChild(ga);
})();
</script>

关于这些代码我想知道将代码放在<script>内但不在<script type="text/javascript">内是否有问题,如果问题放在</head>之前(如建议的那样) for&#34; normal&#34; snippet)

我希望你能帮助我,对不起我的英语:)非常感谢!

2 个答案:

答案 0 :(得分:0)

猜猜第一个。它使用异步,并且在加载页面时不依赖于DOM修改。

答案 1 :(得分:0)

对于HTML5,使用<script><script type="text/javascript">并不重要。

至于你的代码放在哪里,通常javascript应该在所有你的css / html加载后位于页面的底部。 Javascript是同步加载的,因此每个文件加载都会阻止页面的其余部分加载,直到特定文件完全加载。并非所有浏览器都完全支持async标记,因此我不会依赖它。相反,您应该使用异步加载器(如requirejsLAB.js)。

至于你应该放置谷歌分析脚本的位置,根据我的经验,它并不重要。听起来你过早地进行了优化 - https://stackoverflow.com/a/385529/5780021。根据谷歌的说明,我认为它应该放在标题中,以便改善他们围绕页面加载速度的统计数据。