所以我在一个容器 div 中有大量的 div (4000-5000) [每个都包含跨度、 anchor 、图像等],基本上我将它们的显示设置为无或根据条件阻止。这确实需要一些时间。
在寻找更快的东西时,我看到了这个页面 https://developers.google.com/speed/articles/javascript-dom解决方案是从 DOM 中删除容器 div,并通过 getElementsByTagName 迭代包含的元素。
/**
* 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);
}
};
}
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();
}
问题是我无法使用所提供的解决方案,因为我需要通过 ID 访问子元素,但我不能这样做,因为这些元素已从 DOM 中删除。有什么办法可以实现吗?
我也尝试删除容器 div 并将其附加到 documentfragment,但是当它们在 documentfragment 中时,我仍然无法通过它们的 ID 访问 5000 个元素
最后,我也尝试了这个:
document.getElementById("CONTAINERDIV").style.display = "none";
//iterate through the 5000 children divs and change their classname
document.getElementById("CONTAINERDIV").style.display = "block";
因为我希望它不会为每次迭代触发回流,但这似乎并没有提供所需时间的改进。
有没有人对此有任何想法?
最佳答案
我会尽量按要求提供来源。
第一个解决方案 - 最好的解决方案
根据这个网站:JavaScript Grid with One Million Records
您可以学到几件重要的事情:
- 大量DOM节点导致渲染变慢
- JavaScript 数组可以处理大型数据集
- 遍历大型数组很快
- 通过为 Array.sort() 提供自定义函数对数组进行排序速度很快
- eval() 很慢,不应该在大循环中使用
因此,我建议您构建一个数组来快速处理您的元素。
第二种方案
取自该站点的另一个解决方案:Processing large amounts of data in JavaScript
将使用超时(听起来很奇怪)来提高处理程序的速度。
创意来自Book: Secrets of the JavaScript Ninja
关于javascript - 与容器内的大量元素快速交互(DOM、javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22195771/