本文翻译整理自:[url]http://yuiblog.com/blog/2008/07/22/non-blocking-scripts/[/url]
所有浏览器在下载JS的时候,会阻止一切其他活动,比如其他资源的下载,内容的呈现等等。直到JS下载、解析、执行完毕后才开始继续并行下载其他资源并呈现内容。为了提高用户体验,新一代浏览器都支持并行下载JS,但是JS下载仍然会阻塞其它资源的下载(例如.图片,css文件等)
外部js脚本加载的时候常常会遇到脚本阻塞的问题,有什么解决方法呢?
1.there is an easy way to work around this problem: use dynamic scripts tags and load scripts in parallel, improving the page loading speed and the user experience.使用动态script 标签,并行加载script,提高页面加载速度。
2.当然还有一种方法就是:把脚本放在页面最底端,</body>标签前。
同理,不影响ie中加载样式表时间,但是在ff中能提高加载时间,可以这样解决:
文中还指出了其他防止阻塞的几种方法:
3.Using defer attribute of the script tag使用defer属性(IE有效)
4.使用eval()--不安全,非常耗性能,不赞成使用
5.通过XHR请求创建script标签
6.使用iframe
所有浏览器在下载JS的时候,会阻止一切其他活动,比如其他资源的下载,内容的呈现等等。直到JS下载、解析、执行完毕后才开始继续并行下载其他资源并呈现内容。为了提高用户体验,新一代浏览器都支持并行下载JS,但是JS下载仍然会阻塞其它资源的下载(例如.图片,css文件等)
外部js脚本加载的时候常常会遇到脚本阻塞的问题,有什么解决方法呢?
1.there is an easy way to work around this problem: use dynamic scripts tags and load scripts in parallel, improving the page loading speed and the user experience.使用动态script 标签,并行加载script,提高页面加载速度。
var js = document.createElement('script');
js.src = 'myscript.js';
var head = document.getElementsByTagName('head')[0];
head.appendChild(js);
2.当然还有一种方法就是:把脚本放在页面最底端,</body>标签前。
同理,不影响ie中加载样式表时间,但是在ff中能提高加载时间,可以这样解决:
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);
文中还指出了其他防止阻塞的几种方法:
3.Using defer attribute of the script tag使用defer属性(IE有效)
4.使用eval()--不安全,非常耗性能,不赞成使用
5.通过XHR请求创建script标签
6.使用iframe