How to optimally render large amounts of DOM elements using javascript?

Alex Zaretsky picture Alex Zaretsky · Apr 14, 2012 · Viewed 10k times · Source

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 is the hash of allowed items' ids

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?

Thanks for your answers in advance.

Answer

Joseph picture Joseph · Apr 14, 2012

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.

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.

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?