来自国外的页面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 相关文章推荐
彪哥1.1(智能表格)提供下载
Sep 07 Javascript
javaScript 简单验证代码(用户名,密码,邮箱)
Sep 28 Javascript
JavaScript 以对象为索引的关联数组
May 19 Javascript
JavaScript 基础篇之对象、数组使用介绍(三)
Apr 07 Javascript
jQuery中after的两种用法实例
Jul 03 Javascript
javascript中style.left和offsetLeft的用法说明
Mar 07 Javascript
jQuery实现的向下图文信息滚动效果
May 03 Javascript
浅谈JS的基础类型与引用类型
Sep 13 Javascript
vue router路由嵌套不显示问题的解决方法
Jun 17 Javascript
Vue 实现树形视图数据功能
May 07 Javascript
使用element-ui table expand展开行实现手风琴效果
Mar 15 Javascript
layui 数据表格复选框实现单选功能的例子
Sep 19 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一个找二层目录的小东东
2012/08/02 PHP
PHP基于面向对象实现的留言本功能实例
2018/04/04 PHP
PHP日志LOG类定义与用法示例
2018/09/06 PHP
javascript全局变量封装模块实现代码
2012/11/28 Javascript
利用javascript实现全部删或清空所选的操作
2014/05/27 Javascript
jQuery的animate函数学习记录
2014/08/08 Javascript
每天一篇javascript学习小结(属性定义方法)
2015/11/19 Javascript
JavaScript小技巧整理
2015/12/30 Javascript
JavaScript拖拽、碰撞、重力及弹性运动实例分析
2016/01/08 Javascript
AngularJS指令与指令之间的交互功能示例
2016/12/14 Javascript
微信小程序图片选择、上传到服务器、预览(PHP)实现实例
2017/05/11 Javascript
vue基于mint-ui的城市选择3级联动的示例
2017/10/25 Javascript
JavaScript位置参数实现原理及过程解析
2020/09/14 Javascript
Vertx基于EventBus发送接受自定义对象
2020/11/16 Javascript
JS指定音频audio在某个时间点进行播放
2020/11/28 Javascript
[00:35]2016完美“圣”典风云人物:冷冷宣传片
2016/12/08 DOTA
Python的Flask框架与数据库连接的教程
2015/04/20 Python
Django中URLconf和include()的协同工作方法
2015/07/20 Python
Django实现全文检索的方法(支持中文)
2018/05/14 Python
Python基于最小二乘法实现曲线拟合示例
2018/06/14 Python
numpy使用fromstring创建矩阵的实例
2018/06/15 Python
python3利用tcp实现文件夹远程传输
2018/07/28 Python
10分钟教你用python动画演示深度优先算法搜寻逃出迷宫的路径
2019/08/12 Python
解决pytorch GPU 计算过程中出现内存耗尽的问题
2019/08/19 Python
Django REST framework 单元测试实例解析
2019/11/07 Python
pytorch1.0中torch.nn.Conv2d用法详解
2020/01/10 Python
Django模型验证器介绍与源码分析
2020/09/08 Python
python中delattr删除对象方法的代码分析
2020/12/15 Python
澳大利亚家具和家居用品在线商店:Interiors Online
2018/03/05 全球购物
英国第一的滑雪服装和装备零售商:Snow+Rock
2020/02/01 全球购物
童装店创业计划书
2014/01/09 职场文书
会计辞职信范文
2014/01/15 职场文书
金融学专科生自我鉴定
2014/02/21 职场文书
教师师德工作总结2015
2015/07/22 职场文书
升职感谢领导的话语及升职感谢信
2019/06/24 职场文书
jQuery class属性操作addClass()与removeClass()、hasClass()、toggleClass()
2021/03/31 jQuery