我有一些<script>元素,其中一些代码依赖于其他<script>元素中的代码。我看到defer属性在这里可以派上用场,因为它允许延迟代码块的执行。

为了测试它,我在Chrome上执行了这个:http://jsfiddle.net/xXZMN/。

<script defer="defer">alert(2);</script>
<script>alert(1)</script>
<script defer="defer">alert(3);</script>

然而,它提醒2 - 1 - 3。为什么它不提醒1 - 2 - 3?


当前回答

更新:2/19/2016

这个答案已经过时了。有关更新的浏览器版本的信息,请参考这篇文章中的其他答案。


基本上,defer告诉浏览器在执行脚本块中的javascript之前等待“直到它准备好了”。这通常发生在DOM完成加载和文档之后。readyState == 4

延迟属性是internet explorer特有的。在Internet Explorer 8中,在Windows 7中,我在JS Fiddle测试页面中看到的结果是,1 - 2 - 3。

结果可能因浏览器而异。

http://msdn.microsoft.com/en-us/library/ms533719 (v = vs.85) . aspx

与人们普遍认为的IE遵循标准的情况相反,实际上“defer”属性是在DOM级别1规范http://www.w3.org/TR/REC-DOM-Level-1/level-one-html.html中定义的

W3C对defer的定义:http://www.w3.org/TR/REC-html40/interact/scripts.html#adef-defer:

当设置时,这个布尔属性向用户代理提供了一个提示,提示脚本不会生成任何文档内容(例如,没有“文档”。这样,用户代理就可以继续解析和渲染了。

其他回答

还应该注意的是,在IE<=9中,在某些情况下使用脚本延迟可能会出现问题。更多相关信息:https://github.com/h5bp/lazyweb-requests/issues/42

因为defer属性只适用于带有src的脚本标签。找到了一种方法来模拟内联脚本的延迟。使用DOMContentLoaded事件。

<script defer src="external-script.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
    // Your inline scripts which uses methods from external-scripts.
});
</script>

这是因为,DOMContentLoaded事件在延迟带属性脚本完全加载后触发。

defer属性是一个布尔属性。

当出现时,它指定当页面完成解析时执行脚本。

注意:defer属性仅用于外部脚本(应该仅在src属性存在时使用)。

注意:有几种方式可以执行外部脚本:

如果出现async:脚本将与页面的其余部分异步执行(在页面继续解析时将执行脚本) 如果async不存在,而defer存在:当页面完成解析时执行脚本 如果async和defer都不存在:在浏览器继续解析页面之前,立即获取并执行脚本

defer属性仅用于外部脚本(只有在src属性存在时才应该使用)。

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed. Since this feature hasn't yet been implemented by all other major browsers, authors should not assume that the script’s execution will actually be deferred. Never call document.write() from a defer script (since Gecko 1.9.2, this will blow away the document). The defer attribute shouldn't be used on scripts that don't have the src attribute. Since Gecko 1.9.2, the defer attribute is ignored on scripts that don't have the src attribute. However, in Gecko 1.9.1 even inline scripts are deferred if the defer attribute is set.

延迟工作与chrome, firefox, ie > 7和Safari

裁判:https://developer.mozilla.org/en-US/docs/HTML/Element/script