0

我目前正在为我的硕士论文编写一些代码。我有几个关于有效 DOM 操作的问题。

1) 考虑到您必须在彼此靠近的多个节点上执行一堆 DOM 操作。制作所有这些节点的最顶层 parentNode 的深层副本(并将其保留在 DOM 之外),在该子树上执行操作,然后将其与 DOM 中的对应物交换是否有意义。这会最小化浏览器重排/重新渲染吗?

2) 更改节点的 innerHTML 是否比操作它的子树性能更高/更低?

3) 关于在 vanilla javaScript 中进行有效的 DOM 操作(没有任何框架/库),您可以给我更多好的建议吗?

先感谢您!

4

2 回答 2

1

为了防止浏览器过度渲染,最重要的事情是确保您对读取和写入进行分组。

如果你需要对几个节点做某事,并且需要从它们读取一些东西,那么你应该先从所有节点读取,然后再写入所有节点。

DOM 的工作方式是每次您需要读取它时,它都会检查它是否已更改。如果是,浏览器将重新呈现。

因此,首先选择所有元素,缓存您需要获取的信息,然后设置所有元素。

于 2014-12-05T09:58:26.527 回答
0

1) Consider you had to perform a bunch of DOM manipulation on a number of nodes that are close to each other. Would it make sense to make a deep copy of the topmost parentNode of all of those nodes (and keep it outside the DOM), perform the manipulations on that subtree and then swap it with it's counterpart in the DOM. Would this minimize browser reflow/re-rendering?

Yes - do the changes on the counterpart

2) Is changing the innerHTML of a node more/less performant than manipulating it's subtree?

More performant - because you do the stringmanipulation outside dom

3) Is there any more good advice you can give me on efficient DOM manipulation in vanilla javaScript (without any frameworks/libraries)?

document.createDocumentFragment() is the best fully controllable virtual dom ever

于 2019-04-28T21:48:23.613 回答