异步加载JS的五种方式

方案一:<script>标签的async="async"属性(详细参见:script标签的async属性)
点评:HTML5中新增的属性,Chrome、FF、IE9&IE9+均支持(IE6~8不支持)。此外,这种方法不能保证脚本按顺序执行。
方案二:<script>标签的defer="defer"属性
点评:兼容所有浏览器。此外,这种方法可以确保所有设置defer属性的脚本按顺序执行。
方案三:动态创建<script>标签
示例:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
(function(){
var s = document.createElement_x('script');
s.type = 'text/javascript';
s.src = "http://code.jquery.com/jquery-1.7.2.min.js";
var tmp = document.getElementsByTagName_r('script')[0];
tmp.parentNode.insertBefore(s, tmp);
})();
</script>
</head>
<body>
<img src="http://xybtv.com/uploads/allimg/100601/48-100601162913.jpg" />
</body>
</html>
点评:兼容所有浏览器。
方案四:AJAX eval(使用AJAX得到脚本内容,然后通过eval_r(xmlhttp.responseText)来运行脚本)
点评:兼容所有浏览器。
方案五:iframe方式(这里可以参照:iframe异步加载技术及性能 中关于Meboo的部分)
点评:兼容所有浏览器。

猜你喜欢

转载自blog.51cto.com/3928405/2154652