浏览器在找到 <script>
时阻止页面解析和渲染的原因之一标签是允许脚本修改DOM。
来自Load Non-blocking JavaScript with HTML5 Async and Defer :
The defer Attribute
The defer attribute makes a solemn promise to the browser. It states that your JavaScript does not contain any document.write or DOM modification nastiness:
The browser will begin to download file.js and other deferred scripts in parallel without stopping page processing.defer was implemented in Internet Explorer version 4.0 — over 12 years ago! It’s also been available in Firefox since version 3.5.While all deferred scripts are guaranteed to run in sequence, it’s difficult to determine when that will occur. In theory, it should happen after the DOM has completely loaded, shortly before the DOMContentLoaded event. In practice, it depends on the OS and browser, whether the script is cached, and what other scripts are doing at the time.
据我了解,defer
属性代表与浏览器的“契约(Contract)”,您的脚本不会更改 DOM。 async
也是如此?
(当然,这并不妨碍您加载使用 async
更改 DOM 的脚本 - 您只需构建代码,以便在文档准备好或加载时完成 DOM 更改)。
最佳答案
不,事实并非如此,并且不要相信您链接到的那篇文章。 defer
and async
属性告诉浏览器何时应该执行脚本以及加载脚本时解析是否应该等待。它没有做出任何 promise 。
因此,使用这些属性中的任何一个都会阻止 document.write
在脚本的位置写入,并且在 defer
的情况下,启用直接 DOM 修改以影响在 script
元素之后解析的 DOM 元素。
关于javascript - async 属性是否代表不更改 DOM 的契约?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33235209/