插入前端库(例如 Analytics):为什么不是简单的 <script> 标签?

Insert Front-End Library (eg. Analytics): why not a simple <script> tag?

为了插入 GA 代码(以及几乎所有其他 JS 库),代码片段是:

<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-XXXXXX-X', 'auto');
  ga('send', 'pageview');

</script>

为什么不呢:

<script type="text/javascript" src="//www.google-analytics.com/analytics.js" async></script>

body的结尾?

第一个原因是某些脚本需要在创建 html 之前 运行,第二个不在外部脚本中的原因是您需要覆盖一些值.

 ga('create', 'UA-XXXXXX-X', 'auto');

您必须将自己的 GA 帐户放在这里,因此将这么短的脚本放在外部文件中是没有意义的。这样做是为了便于使用,因此即使是初级开发人员和非开发人员也可以向页面添加分析。

如评论中所述,Google 只是提供了一个具有最大浏览器支持的白痴脚本块。

具体来说,IE9 不支持 async 属性。参见 http://caniuse.com/#search=script-async

根据 Google 的 docs,他们确实推荐更简单的 <script src> 版本,但 如果您的目标是现代浏览器(不包括 IE 9)。

Google 知道他们拥有的脚本不依赖于页面中的任何其他脚本,因此他们强制执行脚本作为 'non-blocking' 意味着脚本内容尽快执行, 在文档中通常的标签排序之外(它没有任何依赖关系)。

implementation of the DOM script tag is non-trivial and must cater for script inter-dependencies, unless explicitly stated as 'async'。在这种情况下,外部代码将立即执行,无需等待页面上的任何其他内容加载。

Google have documented their approach well here。基本上它将通过允许 async 脚本执行来提高旧浏览器的性能。动态插入脚本标签模仿现代浏览器中本机 async 属性的行为。您可以看到动态脚本标记在其代码注入器功能中被标记为 async,以适应现代浏览器。

a.async=1;