进入正题之前,先考大家一个问题:defer 属性现在有哪些浏览器支持?

喜悦

除了 defer 属性,script 还新增了一个 async 属性,请看 MDC

async Requires Gecko 1.9.2
This Boolean attribute is set to indicate that the browser should, if possible, execute the script asynchronously. If the script cannot be executed asynchronously, or the browser doesn’t support this attribute, the script is executed synchronously (and loading the content blocks until the script finishes running).

理想情况下,利用 async 属性,脚本异步加载将变得非常简单:
async-test.js:

var g = 1;

async-test-1.html:

<script src="async-test.js" async="true"></script>
<script>
    alert(typeof g); // Firefox 3.6 弹出 undefined
</script>

测试页面:async-test-1.html
目前只有 Firefox 3.6 支持 async 属性,希望其它浏览器能迅速跟进。
阅读全文 »