如何使用javascript优化渲染大量的DOM元素? [英] How to optimally render large amounts of DOM elements using javascript?

查看:357
本文介绍了如何使用javascript优化渲染大量的DOM元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在网页上,我有一个非常大的项目列表(例如,产品卡,每个都包含图像和文本) - 大约1000个。我想在客户端上过滤此列表(仅显示那些未过滤掉的项目),但存在渲染性能问题。我应用了一个非常窄的过滤器,只剩下10-20个项目,然后取消它(因此所有项目都必须再次显示),浏览器(非常好的机器上的Chrome)会挂起一两秒钟。

On a web page I have a quite large list of items (say, product cards, each contains image and text) - about 1000 of them. I want to filter this list on client (only those items, which are not filtered away should be shown), but there is a rendering performance problem. I apply a very narrow filter and only 10-20 items remain, then cancel it (so all items have to be shown again), and browser (Chrome on very nice machine) hangs up for a second or two.

我使用以下例程重新呈现列表:

I re-render the list using following routine:

for (var i = 0, l = this.entries.length; i < l; i++) {
    $(this.cls_prefix + this.entries[i].id).css("display", this.entries[i].id in dict ? "block" : "none")
}

dict是哈希允许的项目'ID

dict is the hash of allowed items' ids

此函数本身立即运行,它呈现的状态挂起。是否有比更改DOM元素的display属性更优化的重新渲染方法?

This function itself runs instantly, it's rendering that hangs up. Is there a more optimal re-render method than changing "display" property of DOM elements?

提前感谢您的回答。

推荐答案

为什么要加载1000个项目?首先你应该考虑像分页这样的东西。每页显示约30个项目。这样,你就不会加载那么多。

Why load 1000 items? First you should consider something like pagination. Showing around 30 items per page. that way, you are not loading that much.

然后如果你真的进入循环很多项目,考虑使用超时。 这是一个演示我曾经说过循环的后果。它会阻止UI并导致浏览器延迟,特别是在长循环上。但是当使用计时器时,你会延迟每次迭代,允许浏览器偶尔呼吸,并在下一次迭代开始之前做其他事情。

then if you are really into that "loop a lot of items", consider using timeouts. here's a demo i had once that illustrates the consequences of looping. it blocks the UI and will cause the browser to lag, especially on long loops. but when using timers, you delay each iteration, allowing the browser to breathe once in a while and do something else before the next iteration starts.

另外需要注意的是你应该避免重绘和回流,这意味着避免移动元素和改变样式,通常在没有必要时。另外,另一个技巧是从DOM中删除实际上不可见的节点。如果您不需要显示某些内容,请将其删除。为什么浪费记忆放一些实际上看不到的东西?

another thing to note is that you should avoid repaints and reflows, which means avoid moving around elements and changing styles that often when it's not necessary. also, another tip is to remove from the DOM the nodes that are not actually visible. if you don't need to display something, remove it. why waste memory putting something that isn't actually seen?

这篇关于如何使用javascript优化渲染大量的DOM元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆