来自国外的页面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 相关文章推荐
js监听键盘事件示例代码
Jul 26 Javascript
Table冻结表头示例代码
Aug 20 Javascript
基于jquery的手风琴图片展示效果实现方法
Dec 16 Javascript
js中this的用法实例分析
Jan 10 Javascript
javascript中返回顶部按钮的实现
May 05 Javascript
javascript框架设计之浏览器的嗅探和特征侦测
Jun 23 Javascript
原生JS实现旋转木马式图片轮播插件
Apr 25 Javascript
基于jQuery实现淡入淡出效果轮播图
Jul 31 Javascript
JavaScript实现经纬度转换成地址功能
Mar 28 Javascript
jQuery实现的监听导航滚动置顶状态功能示例
Jul 23 jQuery
Typescript3.9 常用新特性一览(推荐)
May 14 Javascript
如何使用RoughViz可视化Vue.js中的草绘图表
Jan 30 Vue.js
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获取数组中键值最大数组项的索引值
2015/03/17 PHP
php JWT在web端中的使用方法教程
2018/09/06 PHP
PHP预定义接口――Iterator用法示例
2020/06/05 PHP
JavaScript窗口功能指南之在窗口中书写内容
2006/07/21 Javascript
详解new function(){}和function(){}() 区别分析
2008/03/22 Javascript
Javascript继承机制的设计思想分享
2011/08/28 Javascript
基于JQuery的抓取博客园首页RSS的代码
2011/12/01 Javascript
JS实现京东首页之页面顶部、Logo和搜索框功能
2017/01/12 Javascript
常用jQuery选择器汇总
2017/02/02 Javascript
Bootstrap table学习笔记(2) 前后端分页模糊查询
2017/05/18 Javascript
详解前端路由实现与react-router使用姿势
2017/08/07 Javascript
vue项目中axios使用详解
2018/02/07 Javascript
浅谈Vue2.0中v-for迭代语法的变化(key、index)
2018/03/06 Javascript
vue获取元素宽、高、距离左边距离,右,上距离等还有XY坐标轴的方法
2018/09/05 Javascript
Vue中的v-for指令不起效果的解决方法
2018/09/27 Javascript
微信小程序自定义toast弹窗效果的实现代码
2018/11/15 Javascript
详解js 创建对象的几种方法
2019/03/08 Javascript
微信小程序城市选择及搜索功能的方法
2019/03/22 Javascript
Vuex的actions属性的具体使用
2019/04/14 Javascript
仿ElementUI实现一个Form表单的实现代码
2019/04/23 Javascript
Layui实现数据表格中鼠标悬浮图片放大效果,离开时恢复原图的方法
2019/09/11 Javascript
ionic2.0双击返回键退出应用
2019/09/17 Javascript
BootStrap前端框架使用方法详解
2020/02/26 Javascript
[02:07]TI9显影之尘系列 - Vici Gaming
2019/08/20 DOTA
Python urlopen 使用小示例
2008/09/06 Python
Python assert关键字原理及实例解析
2019/12/13 Python
IE兼容css3圆角的实现代码
2011/07/21 HTML / CSS
基于css3的属性transition制作菜单导航效果
2015/09/01 HTML / CSS
HTML5 body设置自适应全屏
2020/05/07 HTML / CSS
台湾最大网路书店:博客来
2018/03/18 全球购物
英国乡村时尚和宠物用品专家:Pet & Country
2018/07/02 全球购物
全国道德模范事迹
2014/02/01 职场文书
学校党的群众路线教育实践活动对照检查材料
2014/09/24 职场文书
MySQL系列之开篇 MySQL关系型数据库基础概念
2021/07/02 MySQL
Python Flask搭建yolov3目标检测系统详解流程
2021/11/07 Python
微信小程序实现轮播图指示器
2022/06/25 Javascript