gpt4 book ai didi

javascript - 流外 DOM 操作

转载 作者:太空宇宙 更新时间:2023-11-03 21:41:31 25 4
gpt4 key购买 nike

https://developers.google.com/speed/articles/javascript-dom得到这个

据我了解,添加/删除元素会导致回流。就像改变类(Class)一样。但是在解决方案中,您正在追加删除,因此导致问题代码的回流次数两倍。当然,并不是所有的回流都是平等的,所以类名更改回流是否比附加/删除回流更昂贵?我缺少什么使解决方案代码比问题代码更有效?

This pattern lets us create multiple elements and insert them into the DOM triggering a single reflow. It uses something called a DocumentFragment. We create a DocumentFragment outside of the DOM (so it is out-of-the-flow). We then create and add multiple elements to this. Finally, we move all elements in the DocumentFragment to the DOM but trigger a single reflow.

The problem

Let's make a function that changes the className attribute for all anchors within an element. We could do this by simply iterating through each anchor and updating their href attributes. The problems is, this can cause a reflow for each anchor.

function updateAllAnchors(element, anchorClass) {
var anchors = element.getElementsByTagName('a');
for (var i = 0, length = anchors.length; i < length; i ++) {
anchors[i].className = anchorClass;
}
}

The solution

To solve this problem, we can remove the element from the DOM, update all anchors, and then insert the element back where it was. To help achieve this, we can write a reusable function that not only removes an element from the DOM, but also returns a function that will insert the element back into its original position.

/**
* Remove an element and provide a function that inserts it into its original position
* @param element {Element} The element to be temporarily removed
* @return {Function} A function that inserts the element into its original position
**/
function removeToInsertLater(element) {
var parentNode = element.parentNode;
var nextSibling = element.nextSibling;
parentNode.removeChild(element);
return function() {
if (nextSibling) {
parentNode.insertBefore(element, nextSibling);
} else {
parentNode.appendChild(element);
}
};
}

Now we can use this function to update the anchors within an element that is out-of-the-flow, and only trigger a reflow when we remove the element and when we insert the element.

function updateAllAnchors(element, anchorClass) {
var insertFunction = removeToInsertLater(element);
var anchors = element.getElementsByTagName('a');
for (var i = 0, length = anchors.length; i < length; i ++) {
anchors[i].className = anchorClass;
}
insertFunction();
}

最佳答案

假设您要更改 100 万个元素的类。

直接这样做会导致 100 万次回流 - 每个类一个 -。

但是如果您从 DOM 中移除它的父级,更改所有类,然后将其插入回来,那只有 2 次回流 - 因为更改文档外的元素不会导致回流。

所以基本上,如果您有很多元素,删除和重新插入会更有效。如果您只有几个,则无需这样做。

关于javascript - 流外 DOM 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23226971/

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