为什么Google Analytics会动态地将javascript注入页面

为什么Google Analytics会动态地将javascript注入页面,javascript,google-analytics,Javascript,Google Analytics,为什么我需要使用: (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.getEle

为什么我需要使用:

(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 async="true" type="text/javascript" src="http://www.google-analytics.com/ga.js"></script>

我能看到的唯一原因是他们有一个不同的SSL子域。如果不是因为这个原因,有什么理由使用这种脚本注入技术吗

  • 能够根据父页面的协议提供
    http
    https
    是一个原因

  • 由于脚本是通过运行JS代码插入的
    script
    标记注入的,因此它不会阻止页面加载。这是另一个原因。但这也可以通过新的HTML5属性实现(但这与旧浏览器不兼容,GA绝对需要与几乎所有浏览器兼容)


  • 主要是点2(和子域)。第1点可以通过(…
    src=“//www.google-analytics.com/ga.js”
    …)@T.J.Crowder解决-是的,这也是正确的,但它适用于所有浏览器,包括旧浏览器。Bcoz GA必须与我想象中的一切超级兼容。此外,
    location.protocol
    可用于动态检测正确的协议。@techfoobar:与任何您想要抛出的协议兼容,请参阅我添加的链接。:-)@T.J.Crowder-感谢您提供的信息丰富的文章。因此,这与async的结合应该意味着没有更多的脚本,可能还需要几年时间。。