Minimizing browser reflow/re-rendering

890 views Asked by At

I'm currently working on some code for my master's thesis. I've a few questions regarding effective DOM manipulation.

1) Consider you had to perform a bunch of DOM manipulation on a number of nodes that are close to each other. Would it make sense to make a deep copy of the topmost parentNode of all of those nodes (and keep it outside the DOM), perform the manipulations on that subtree and then swap it with it's counterpart in the DOM. Would this minimize browser reflow/re-rendering?

2) Is changing the innerHTML of a node more/less performant than manipulating it's subtree?

3) Is there any more good advice you can give me on efficient DOM manipulation in vanilla javaScript (without any frameworks/libraries)?

Thank you in advance!

2

There are 2 answers

0
Etai On

The most important thing to do in order to prevent excessive browser rendering is to make sure you group your reads and writes.

If you need to do something to several nodes, and need to read something from them, then you should read from all the nodes first, and then write to all.

The way the DOM works is that each time you need to read from it, it checks if it was changed. If it was, the browser will rerender.

Therefore, first select all the elements, cache the info you need to get, then set on all of them.

0
AudioBubble On

1) Consider you had to perform a bunch of DOM manipulation on a number of nodes that are close to each other. Would it make sense to make a deep copy of the topmost parentNode of all of those nodes (and keep it outside the DOM), perform the manipulations on that subtree and then swap it with it's counterpart in the DOM. Would this minimize browser reflow/re-rendering?

Yes - do the changes on the counterpart

2) Is changing the innerHTML of a node more/less performant than manipulating it's subtree?

More performant - because you do the stringmanipulation outside dom

3) Is there any more good advice you can give me on efficient DOM manipulation in vanilla javaScript (without any frameworks/libraries)?

document.createDocumentFragment() is the best fully controllable virtual dom ever