在标记与标记之前包含Javascript的优缺点是什么?

前端之家收集整理的这篇文章主要介绍了在标记与标记之前包含Javascript的优缺点是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
编辑:虽然在( 1),( 2),( 3)之前已经询问并回答了这个问题,但是当在< head>中包含文件时,答案没有提到使用异步和/或延迟加载的可能性.由于谷歌分析新代码使用这两种方法,我被提示提出问题.

我最近注意到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>?

解决方法

关于< head>的建议是不链接到需要下载的EXTERNAL脚本.这阻止了并行下载.谷歌最新的跟踪代码使用 lazy loading,并不阻止并行下载.
(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);
  })();
原文链接:https://www.f2er.com/js/158459.html

猜你在找的JavaScript相关文章