相信很多与页面打过交道的同学都对 Yahoo 的 Best Practices for Speeding Up Your Web Site 不陌生。而这 35 条最佳实践中,对 Javascript 的加载顺序的要求是:Put Scripts at the Bottom。因为根据 HTTP/1.1 specification 看来,在同一时间加载两个文件是最理想的,而 Javascript 脚本会阻碍平行下载。Steve 说那是 2008 – 2009 那个时代用的。现在,加载 Javascript 已经有了革命性的化变。
在开讲之前,有一个必须解决的问题是:为什么我们要把 JS 文件放在 之前的最底部。根本原因是,它不能平行下载。而其实并不是所有浏览器都不支持。现在大部分浏览器都支持 Script 的平行下载,除了老掉牙的 IE6&7、Firefox 2&3.0、 Safari 3、Chrome 1。但我们最熟悉的老掉牙同学 IE6 (或以IE为核的那些壳)还是中国(甚至世界上)市场上占用率最高的浏览器,因此我们需要一个折衷的方案。
我们有6种方法可以实现平行(NON-Blocking)下载:
eval()
执行 responseText.。
src
指向脚本URL.
defer
属性
document.write
Script Tag – 利用 document.write
把 <script src="">
添加到 HTML 中。但这个只对 IE 有效。 兼容性可看下图:
Technique | Parallel Downloads | Differ | Existing Scripts | Busy Indicators | Ensures Order | Size (bytes) |
---|---|---|---|---|---|---|
XHR Eval | IE, FF, Saf, Chr, Op | no | no | Saf, Chr | - | ~500 |
XHR Injection | IE, FF, Saf, Chr, Op | no | yes | Saf, Chr | - | ~500 |
Script in Iframe | IE, FF, Saf, Chr, Op | no | no | IE, FF, Saf, Chr | - | ~50 |
Script DOM Element | IE, FF, Saf, Chr, Op | yes | yes | FF, Saf, Chr | FF, Op | ~200 |
Script Defer | IE, Saf4, Chr2, FF3.1 | yes | yes | IE, FF, Saf, Chr, Op | IE, FF, Saf, Chr, Op | ~50 |
document.write Script Tag | IE, Saf4, Chr2, Op | yes | yes | IE, FF, Saf, Chr, Op | IE, FF, Saf, Chr, Op | ~100 |
Which solution should be used? It all depends on your own needs. This diagram describes when to use which method:
Overall, Script DOM Element is a better solution. NCZ’s blog mentioned that the best technology currently is:
<script>
introduces the first file in the page body (before ).
Create a second 创建第二个 <script>
<script>
to execute the function of downloading the second Javascript file and other initialization code. Based on the technology mentioned above. NCZ recommends that the first file only contains the corresponding code to dynamically load the second file:
Then, we can do this in the page:
4. Practice
YUI3's Loader uses NCZ's method. And in Alipay. We also used a similar approach. Let’s talk briefly here.
When in use, use Loader.use() to implement dynamic loading of code. Of course, there is not only dynamic loading, but also a certain caching mechanism. It is recommended that you check out the related combo service technology. At present, the workers in the Alipay front-end architecture team have made some good progress in this area (according to the test report, the speed is very good, and it may be open sourced at the appropriate time).
5. Summary
Front-end performance optimization. There is much more that can be done. And, with the emergence of HTML5 technology and the continuous innovation of Javascript technology, I believe there are more things to look forward to. Front-ends, come on, there are many things in the future that should be led by you.
Reference: