加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

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

发布时间:2020-12-14 23:50:14 所属栏目:资源 来源:网络整理
导读:所以我在容器div中有大量的div(4000-5000)[每个包含跨度,锚点,图像等],基本上我将它们的显示设置为none或基于条件阻止.这确实需要一些时间. 在我搜索更快的东西时,我遇到了这个页面https://developers.google.com/speed/articles/javascript-dom,解决方案是
所以我在容器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,性能提升更加明显.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读