javascript - <script defer ="defer"> 到底是如何工作的?

标签 javascript html deferred-execution

我有一些<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

最佳答案

HTML5 规范中的一些片段:http://w3c.github.io/html/semantics-scripting.html#element-attrdef-script-async

The defer and async attributes must not be specified if the src attribute is not present.

<小时/>

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.

<小时/>

If the element has a src attribute, and the element has a defer attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute:

The element must be added to the end of the list of scripts that will execute when the document has finished parsing associated with the Document of the parser that created the element.

关于javascript - &lt;script defer ="defer"> 到底是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20333860/

相关文章:

javascript - 是否可以判断是否由于安装了应用程序而打开了覆盖新标签页?

javascript - 如何将 css 类添加到一组链接中的特定链接?

html - CSS/HTML - 为什么我的链接没有变黑?

html - 导航栏链接在网站上不可点击

javascript - 用于拆分字符串但捕获分隔符的正则表达式

javascript - 如何使用 Q 链接嵌套的 Promise?我无法让它们按正确的顺序运行

jquery - JQuery Mobile Page如何添加 flex 弹跳效果?

c# - 使用函数结果作为源的 LINQ 延迟执行(例如 Console.ReadLine)

python - appengine 延迟任务问题,执行抛出未知错误

Javascript/AngularJS - 等待回调完成执行