Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 914
Alex Zaretsky Avatar asked Apr 14 '12 05:04

Alex Zaretsky


2 Answers

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?

like image 188
Joseph Avatar answered Oct 20 '22 04:10

Joseph


Dude - the best way to handle "large amounts of DOM elements" is to NOT do it on the client, and/or DON'T use Javascript if you can avoid it.

If there's no better solution (and I'm sure there probably is!), then at LEAST partition your working set down to what you actually need to display at that moment (instead of the whole, big, honkin' enchilada!)

like image 43
paulsm4 Avatar answered Sep 19 '22 23:09

paulsm4