gpt4 book ai didi

javascript - 为什么不应该使用延迟脚本修改 DOM?

转载 作者:行者123 更新时间:2023-12-02 16:59:35 25 4
gpt4 key购买 nike

我正在温习我的 javascript 基础知识,我正在阅读的书说明了以下内容(转述):

“在 script 元素中添加 defer 属性是向浏览器 promise ,您的脚本不会对 DOM 进行任何更改”

我很好奇为什么会这样?由于延迟脚本直到渲染完成后才会执行,因此我认为修改脚本中的 DOM 是安全的。

最佳答案

这是关于“DOM”含义的术语混淆。咨询HTML4 spec on defer给我们一个关于到底发生了什么的提示:

When set, this boolean attribute provides a hint to the user agent that the script is not going to generate any document content (e.g., no "document.write" in javascript) and thus, the user agent can continue parsing and rendering.

那么,你的书的意思是什么

your script will not be making changes to the DOM

确实

your script will not be making changes to the document text being parsed

您的释义引用使用短语“DOM”来指代正在解析的 HTML 文档文本,而不是由该解析创建的可通过 JavaScript 访问的对象模型。延迟脚本在解析后没有理由不能改变 DOM 结构(即 document 中的结构),但它肯定不能改变正在解析的文档文本,因为文档已经被解析了。脚本运行时已完全解析。

关于javascript - 为什么不应该使用延迟脚本修改 DOM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25870424/

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