gpt4 book ai didi

js: removing multiple nodes from DOM without multiple reflows(JS:从没有多个回流的DOM中移除多个节点)

转载 作者:bug小助手 更新时间:2023-10-28 11:33:19 26 4
gpt4 key购买 nike



i need to add and remove multiple node from DOM while scrolling. To add nodes i found the solution of documentFragment, which allows me to add multiple node with only one reflow.

我需要添加和删除多个节点从DOM,而滚动。为了添加节点,我找到了documentFragment的解决方案,它允许我只使用一个回流来添加多个节点。



But removing a great number of nodes is very costly too, so i'm searching for a faster solution.

但删除大量节点的成本也非常高,因此我正在寻找更快的解决方案。



Now I remove every child with a Node.removeChild(...), which causes a reflow.

现在我用Node.removeChild(...)删除每个子节点,这导致回流。



Thanks

谢谢


更多回答

Should you manipulate HTML string instead of DOM? I think it will have only one reflow after manipulating HTML then replace the current HTML

您应该操作HTML字符串而不是DOM吗?我认为在操作HTML之后,它将只有一次回流,然后替换当前的HTML

Problem is that manipulating an HTML string alone will mean that any listeners that may be attached to the elements inside will be corrupted.

问题是,单独操作一个HTML字符串将意味着任何可能附加到内部元素的侦听器都将被破坏。

plus changing the innerHTML attr is very costly i think. Its even better to remove large numbers of elements with reflow everytime, then to set innerHTML = ""

另外,我认为更改innerHTMLattr的成本非常高。更好的做法是每次都使用回流来删除大量元素,然后设置innerHTML=“”

优秀答案推荐

I'm not sure if it has better performance but you can remove the parent element, then remove as many child as you want and after you're done, you re-append it. Since the elements on the dom has not changed, this shouldn't cause a reflow.

我不确定它的性能是否更好,但您可以删除父元素,然后删除任意多个子元素,并在完成后重新追加它。由于DOM上的元素没有更改,这应该不会导致回流。




// just a dumb code to show what I meant

let ol = document.querySelector('ol')
ol.remove()
let arr = [...ol.children] // for not modifying while iterating
for (let el of arr)
if (el.innerHTML != "child") el.remove()
document.body.appendChild(ol)

<ol>
<li>way</li>
<li>too</li>
<li>many</li>
<li>child</li>
<li>to</li>
<li>remove</li>
</ol>




更多回答

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