来自国外的页面JavaScript文件优化


Posted in Javascript onDecember 08, 2010

The problem: scripts block downloads

Let's first take a look at what the problem is with the script downloads. The thing is that before fully downloading and parsing a script, the browser can't tell what's in it. It may contain document.write() calls which modify the DOM tree or it may even contain location.href and send the user to a whole new page. If that happens, any components downloaded from the previous page may never be needed. In order to avoid potentially useless downloads, browsers first download, parse and execute each script before moving on with the queue of other components waiting to be downloaded. As a result, any script on your page blocks the download process and that has a negative impact on your page loading speed.

Here's how the timeline looks like when downloading a slow JavaScript file (exaggerated to take 1 second). The script download (the third row in the image) blocks the two-by-two parallel downloads of the images that follow after the script:

来自国外的页面JavaScript文件优化

Here's the example to test yourself.

Problem 2: number of downloads per hostname

Another thing to note in the timeline above is how the images following the script are downloaded two-by-two. This is because of the restriction of how many components can be downloaded in parallel. In IE <= 7 and Firefox 2, it's two components at a time (following the HTTP 1.1 specs), but both IE8 and FF3 increase the default to 6.

You can work around this limitation by using multiple domains to host your components, because the restriction is two components per hostname. For more information of this topic check the article “Maximizing Parallel Downloads in the Carpool Lane” by Tenni Theurer.

The important thing to note is that JavaScripts block downloads across all hostnames. In fact, in the example timeline above, the script is hosted on a different domain than the images, but it still blocks them.

Scripts at the bottom to improve user experience

As Yahoo!'s Performance rules advise, you should put the scripts at the bottom of the page, towards the closing </body> tag. This doesn't really make the page load faster (the script still has to load), but helps with the progressive rendering of the page. The user perception is that the page is faster when they can see a visual feedback that there is progress.

Non-blocking scripts

It turns out that there is an easy solution to the download blocking problem: include scripts dynamically via DOM methods. How do you do that? Simply create a new <script> element and append it to the <head>:

var js = document.createElement('script');

js.src = 'myscript.js';

var head = document.getElementsByTagName('head')[0];

head.appendChild(js);

Here's the same test from above, modified to use the script node technique. Note that the third row in the image takes just as long to download, but the other resources on the page are loading simultaneously:

来自国外的页面JavaScript文件优化

Test example

As you can see the script file no longer blocks the downloads and the browser starts fetching the other components in parallel. And the overall response time is cut in half.

Dependencies

A problem with including scripts dynamically would be satisfying the dependencies. Imagine you're downloading 3 scripts and three.js requires a function from one.js. How do you make sure this works?

Well, the simplest thing is to have only one file, this way not only avoiding the problem, but also improving performance by minimizing the number of HTTP requests (performance rule #1).

If you do need several files though, you can attach a listener to the script's onload event (this will work in Firefox) and the onreadystatechange event (this will work in IE). Here's a blog post that shows you how to do this. To be fully cross-browser compliant, you can do something else instead: just include a variable at the bottom of every script, as to signal “I'm ready”. This variable may very well be an array with elements for every script already included.

Using YUI Get utility

The YUI Get Utility makes it easy for you to use script includes. For example if you want to load 3 files, one.js, two.js and three.js, you can simply do:

var urls = ['one.js', 'two.js', 'three.js'];

YAHOO.util.Get.script(urls);

YUI Get also helps you with satisfying dependencies, by loading the scripts in order and also by letting you pass an onSuccess callback function which is executed when the last script is done loading. Similarly, you can pass an onFailure function to handle cases where scripts fail to load.

var myHandler = {

onSuccess: function(){

alert(':))');

},

onFailure: function(){

alert(':((');

}

};
var urls = ['1.js', '2.js', '3.js'];

YAHOO.util.Get.script(urls, myHandler);

Again, note that YUI Get will request the scripts in sequence, one after the other. This way you don't download all the scripts in parallel, but still, the good part is that the scripts are not blocking the rest of the images and the other components on the page. Here's a good example and tutorial on using YUI Get to load scripts.

YUI Get can also include stylesheets dynamically through the method YAHOO.util.Get.css() [example].

Which brings us to the next question:

And what about stylesheets?

Stylesheets don't block downloads in IE, but they do in Firefox. Applying the same technique of dynamic inserts solves the problem. You can create dynamic link tags like this:

var h = document.getElementsByTagName('head')[0];

var link = document.createElement('link');

link.href = 'mycss.css';

link.type = 'text/css';

link.rel = 'stylesheet';

h.appendChild(link);

This will improve the loading time in Firefox significantly, while not affecting the loading time in IE.

Another positive side effect of the dynamic stylesheets (in FF) is that it helps with the progressive rendering. Usually both browsers will wait and show blank screen until the very last piece of stylesheet information is downloaded, and only then they'll start rendering. This behavior saves them the potential work of re-rendering when new stylesheet rules come down the wire. With dynamic <link>s this is not happening in Firefox, it will render without waiting for all the styles and then re-render once they arrive. IE will behave as usual and wait.

But before you go ahead and implement dynamic <link> tags, consider the violation of the rule of separation of concerns: your page formatting (CSS) will be dependent on behavior (JS). In addition, this problem is going to be addressed in future Firefox versions.

Other ways?

There are other ways to achieve the non-blocking scripts behavior, but they all have their drawbacks.

Method Drawback
Using defer attribute of the script tag IE-only, unreliable even there
Using document.write() to write a script tag Non-blocking behavior is in IE-only document.write is not a recommended coding practice
XMLHttpRequest to get the source then execute with eval(). “eval() is evil” same-domain policy restriction
XHR request to get the source, create a new script tag and set its content more complex same-domain policy
Load script in an iframe complex iframe overhead same-domain policy

Future

Safari and IE8 are already changing the way scripts are getting loaded. Their idea is to download the scripts in parallel, but execute them in the sequence they're found on the page. It's likely that one day this blocking problem will become negligible, because only a few users will be using IE7 or lower and FF3 or lower. Until then, a dynamic script tag is an easy way around the problem.

Summary

  • Scripts block downloads in FF and IE browsers and this makes your pages load slower.
  • An easy solution is to use dynamic <script> tags and prevent blocking.
  • YUI Get Utility makes it easier to do script and style includes and manage dependencies.
  • You can use dynamic <link> tags too, but consider the separation of concerns first.
Javascript 相关文章推荐
会自动逐行上升的文本框
Jun 30 Javascript
jquery异步请求实例代码
Jun 21 Javascript
网页中可关闭的漂浮窗口实现可自行调节
Aug 20 Javascript
jquery获取元素索引值index()示例
Feb 13 Javascript
Node.js事件循环(Event Loop)和线程池详解
Jan 28 Javascript
Node.js 去掉种子(torrent)文件里的邪恶信息
Mar 27 Javascript
jquery实现鼠标悬浮停止轮播特效
Aug 20 Javascript
两行代码轻松搞定JavaScript日期验证
Aug 03 Javascript
Listloading.js移动端上拉下拉刷新组件
Aug 04 Javascript
Agularjs妙用双向数据绑定实现手风琴效果
May 26 Javascript
AngularJS基于http请求实现下载php生成的excel文件功能示例
Jan 23 Javascript
Vue核心概念Action的总结
Jan 18 Javascript
js 替换功能函数,用正则表达式解决,js的全部替换
Dec 08 #Javascript
javascript中callee与caller的用法和应用场景
Dec 08 #Javascript
js下通过prototype扩展实现indexOf的代码
Dec 08 #Javascript
在JQuery dialog里的服务器控件 事件失效问题
Dec 08 #Javascript
jquery蒙版控件实现代码
Dec 08 #Javascript
基于JQuery制作的产品广告效果
Dec 08 #Javascript
关于用Jquery的height()、width()计算动态插入的IMG标签的宽高的问题
Dec 08 #Javascript
You might like
php中Smarty模板初体验
2011/08/08 PHP
php 短链接算法收集与分析
2011/12/30 PHP
php&amp;mysql 日期操作小记
2012/02/27 PHP
解析php通过cookies获取远程网页的指定代码
2013/06/25 PHP
php简单获取目录列表的方法
2015/03/24 PHP
使用EXT实现无刷新动态调用股票信息
2008/11/01 Javascript
图片img的src不变让浏览器重新加载实现方法
2013/03/29 Javascript
JS中的substring和substr函数的区别说明
2013/05/07 Javascript
jquery为页面增加快捷键示例
2014/01/31 Javascript
JS数组的赋值介绍
2014/03/10 Javascript
JavaScript实现基于Cookie的存储类实例
2015/04/10 Javascript
JS实现弹性菜单效果代码
2015/09/07 Javascript
Angular2 环境配置详细介绍
2016/09/21 Javascript
Angular2从搭建环境到开发步骤详解
2016/10/17 Javascript
JavaScript实现三级级联特效
2017/11/05 Javascript
JS实现生成由字母与数字组合的随机字符串功能详解
2018/05/25 Javascript
Vue条件循环判断+计算属性+绑定样式v-bind的实例
2018/09/18 Javascript
JavaScript享元模式原理与用法实例详解
2020/03/09 Javascript
JS数组及对象遍历方法代码汇总
2020/06/16 Javascript
vue实现的多页面项目如何优化打包的步骤详解
2020/07/19 Javascript
如何基于jQuery实现五角星评分
2020/09/02 jQuery
vue项目开启Gzip压缩和性能优化操作
2020/10/26 Javascript
Win7上搭建Cocos2d-x 3.1.1开发环境
2014/07/03 Python
python解析xml文件操作实例
2014/10/05 Python
Python实现读取目录所有文件的文件名并保存到txt文件代码
2014/11/22 Python
Python实现Linux中的du命令
2017/06/12 Python
python使用thrift教程的方法示例
2019/03/21 Python
Python 使用指定的网卡发送HTTP请求的实例
2019/08/21 Python
使用python切片实现二维数组复制示例
2019/11/26 Python
python爬虫开发之Beautiful Soup模块从安装到详细使用方法与实例
2020/03/09 Python
Biblibili视频投稿接口分析并以Python实现自动投稿功能
2021/02/05 Python
捐献物资倡议书范文
2014/05/19 职场文书
幼儿园安全生产月活动总结
2014/07/05 职场文书
党的群众路线教育实践活动教师自我剖析材料
2014/10/09 职场文书
师范生见习自我总结
2015/06/23 职场文书
MyBatis-Plus 批量插入数据的操作方法
2021/09/25 Java/Android