辩论赛:修改 DOM 是同步的还是异步的

正方:修改 DOM 是同步的
反方:修改 DOM 是异步的

正方论词:

The Document Object Model (DOM) is a programming interface for HTML and XML documents. It provides a structured representation of the document and it defines a way that the structure can be accessed from programs so that they can change the document structure, style and content.

https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction

DOM 全称文档对象模型,是一个修改文档结构的接口。

在 Javascript 中,DOM 体现为特定的 Javascript 对象。这类对象和普通对象没有什么区别,对它的修改是同步的。

document.body.firstChild.nodeValue = 'Test';
document.body.firstChild.nodeValue === 'Test'; // true

反方论词:

The Document Object Model (DOM) is a programming interface for HTML and XML documents. It provides a structured representation of the document and it defines a way that the structure can be accessed from programs so that they can change the document structure, style and content.

https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction

DOM 全称文档对象模型,是一个修改文档结构的接口。

换句话说,DOM 是一个修改文档结构的途径。修改 DOM 实际上是在修改文档结构。

在 JS 中,修改 DOM 需要两个环节,JS object 被修改,以及随后的文档结构被修改。

Adding & removing a DOM node is a few pointer swaps, not much more than setting a property on the JS object.
However, layout is slow. When you touch the DOM in any way, you set a dirty bit on the whole tree that tells the browser it needs to figure out where everything goes again. When JS hands control back to the browser, it invokes its layout algorithm (or more technically, it invokes its CSS recalc algorithm, then layout, then repaint, then re-compositing) to redraw the screen. The layout algorithm is quite complex - read the CSS spec to understand some of the rules - and that means it often has to make non-local decisions.

https://news.ycombinator.com/item?id=9155564

修改 DOM 对象仅是改变了 JS object,实际的生效过程还需要经过 layout 才能反映到文档结构上,而这一过程永远是异步的。

既然修改文档结构永远是异步的,而修改文档结构是修改 DOM 中的一个环节,那么修改 DOM 也就永远是异步的了。

@pod2g 你是评委。

关键字:JavaScript, dom, 修改, the

版权声明

本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处。如若内容有涉嫌抄袭侵权/违法违规/事实不符,请点击 举报 进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部