我有一些<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?
看看谷歌开发人员Jake Archibald在2013年写的这篇深入研究脚本加载的文章。
引用该条有关部分:
Defer
<script src="//other-domain.com/1.js" defer></script>
<script src="2.js" defer></script>
Spec says: Download together, execute in order just before DOMContentLoaded. Ignore “defer” on scripts without “src”.
IE < 10 says: I might execute 2.js halfway through the execution of 1.js. Isn’t that fun??
The browsers in red say: I have no idea what this “defer” thing is, I’m going to load the scripts as if it weren’t there.
Other browsers say: Ok, but I might not ignore “defer” on scripts without “src”.
(根据这条评论,我将添加早期版本的Firefox在延迟脚本完成运行之前触发DOMContentLoaded。)
现代浏览器似乎正确地支持异步,但您需要接受脚本无序运行,并且可能在DOMContentLoaded之前运行。
HTML5规范中的一些片段:http://w3c.github.io/html/semantics-scripting.html#element-attrdef-script-async
必须使用defer和async属性
如果SRC属性没有被指定
不存在。
There are three possible modes that
can be selected using these
attributes [async and defer]. If the async attribute is
present, then the script will be
executed asynchronously, as soon as it
is available. If the async attribute
is not present but the defer attribute
is present, then the script is
executed when the page has finished
parsing. If neither attribute is
present, then the script is fetched
and executed immediately, before the
user agent continues parsing the page.
The exact processing details for these
attributes are, for mostly historical
reasons, somewhat non-trivial,
involving a number of aspects of HTML.
The implementation requirements are
therefore by necessity scattered
throughout the specification. The
algorithms below (in this section)
describe the core of this processing,
but these algorithms reference and are
referenced by the parsing rules for
script start and end tags in HTML, in
foreign content, and in XML, the rules
for the document.write() method, the
handling of scripting, etc.
如果元素有src属性,
元素有一个defer属性,
元素被标记为
"parser-inserted"和元素
没有async属性:
元素必须添加到脚本列表的末尾
当文档完成时执行
与文档相关的解析
对象的解析器的
元素。
看看谷歌开发人员Jake Archibald在2013年写的这篇深入研究脚本加载的文章。
引用该条有关部分:
Defer
<script src="//other-domain.com/1.js" defer></script>
<script src="2.js" defer></script>
Spec says: Download together, execute in order just before DOMContentLoaded. Ignore “defer” on scripts without “src”.
IE < 10 says: I might execute 2.js halfway through the execution of 1.js. Isn’t that fun??
The browsers in red say: I have no idea what this “defer” thing is, I’m going to load the scripts as if it weren’t there.
Other browsers say: Ok, but I might not ignore “defer” on scripts without “src”.
(根据这条评论,我将添加早期版本的Firefox在延迟脚本完成运行之前触发DOMContentLoaded。)
现代浏览器似乎正确地支持异步,但您需要接受脚本无序运行,并且可能在DOMContentLoaded之前运行。