javascript - async 属性是否代表不更改 DOM 的契约?

标签 javascript html dom

浏览器在找到 <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/

相关文章:

javascript - Jquery Div 隐藏

c++ - 多次调用 DOMImplementationRegistry::getDOMImplementation() 是否不安全或至少是错误的形式?

javascript - 在 React 上设置innerText

javascript - Meteor Iron-Router 通过 [data] 与 [params] 访问变量

php - 我怎样才能使这个 AJAX/PHP 工作?

html - 如何为 aria-labelledby 使用类选择器?

javascript - 如何为文档内容可编辑的元素设置类属性

javascript - 是否有一种惯用的方法来使用 Prototype 库监听 DOM 的更改?

javascript - 如何在 AJAX 请求期间禁用 anchor 标记并更改 html()

javascript - 如何在 vue 3 中从 setup 调用 prop 函数