究竟是如何工作的?-6ren"> 究竟是如何工作的?-我有几个 元素,其中一些代码依赖于其他 中的代码元素。我看到了defer属性在这里可以派上用场,因为它允许代码块在执行中被推迟。 为了测试它,我在 Chrome 上执行了这个:http://jsfi-6ren">
gpt4 book ai didi

javascript - <script defer ="defer"> 究竟是如何工作的?

转载 作者:IT老高 更新时间:2023-10-28 11:05:36 28 4
gpt4 key购买 nike

我有几个 <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/5250412/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com