来自国外的页面JavaScript文件优化_javascript技巧
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:
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
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
推荐阅读
-
来自国外的页面JavaScript文件优化_javascript技巧
-
js控制页面控件隐藏显示的两种方法介绍_javascript技巧
-
js实现页面跳转重定向的几种方式_javascript技巧
-
iframe子页面与父页面在同域或不同域下的js通信_javascript技巧
-
在浏览器中获取当前执行的脚本文件名的代码_javascript技巧
-
js 优化次数过多的循环 考虑到性能问题_javascript技巧
-
JavaScript检测上传文件大小的方法_javascript技巧
-
javascript - PHP或者JS如何跳转来自chrome Opera 等手机模拟浏览器的用户到不同的页面
-
IE6中使用position导致页面变形的解决方案(js代码)_javascript技巧
-
js计算页面刷新的次数_javascript技巧