微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

快速与容器内的大量元素进行交互(DOM,javascript)

所以我在容器div中有大量的div(4000-5000)[每个包含跨度,锚点,图像等],基本上我将它们的显示设置为none或基于条件阻止.这确实需要一些时间.

在我搜索更快的东西时,我遇到了这个页面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中时,仍然无法通过ID访问5000个元素

最后,我也试过这个:

document.getElementById("CONTAINERDIV").style.display = "none";

//iterate through the 5000 children divs and change their classname

document.getElementById("CONTAINERDIV").style.display = "block";

因为我希望它不会在每次迭代时触发回流,但这似乎并没有提供所需时间的改进.

有没有人对此有任何想法?

解决方法

显示无/块很贵.从我在交易网络平台上提高性能的日子开始,我推荐的一种技术,特别是对旧版浏览器而言,是使用相对位置并使用负左值将其从屏幕上拉出来.当然,根据您的实现,您可能还希望将高度设置为0px,或者查看位置绝对的可能性.核心概念仍然是你只是将元素从屏幕上移开.好消息是隐藏的元素仍然存在于DOM中,您可以访问它们.
div {
  position: relative;
  left: 0px;
}
div.hide {
  left: -4096px;
  height: 0px;
}

看看这两个小提琴,他们创建10K行并切换(隐藏/显示)奇数行:

FIDDLE using Display none/block

FIDDLE using Position and Height

Chrome可以快速处理100K这些行,很难看到显着的性能提升,而对于Firefox,我不得不将行数减少到10K,性能提升更加明显.

原文地址:https://www.jb51.cc/html/227935.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐