DEV Community

Rubin Elezi
Rubin Elezi

Posted on

Stop touching the DOM, damn it!

DOM operations are expensive.

Leaving the DOM alone is a big topic in JavaScript optimization. The classic example is appending an array of list items: if you append each of these to the DOM individually, it is considerably slower than appending them all at once.

Reflow

DOM operations are resource-heavy because of reflow. Reflow is basically the process by which the browser re-renders the DOM elements on the screen. For instance, if you change the width of a div with JavaScript, the browser has to refresh the rendered page to account for this change. Meaning every time you change something on the DOM with javascript the whole page will be rerendered, and you can avoid this by using, documentFragment.

documentFragment

You can view this as a container holding all the node elements that you want to add to the DOM. You store them on this "container" and after you have finished all the changes that you want, you append that container to the DOM. Imagine if you wanted to add 100 div tags if you append them directly the browser would have to rerender the page 100 times, expensive, but if you use documentFragment the browser would need to render only once.

Do you go to the store 100 times to buy 100 things, or do you buy them all at once?

Example

Before

var trash = document.getElementById("trash");
// ... Modify trash
document.getElementById("target").appendChild(trash);
After

var trash = document.getElementById("trash");
var frag = document.createDocumentFragment();
frag.appendChild(trash);
// ... Modify trash
document.getElementById("target").appendChild(frag.cloneNode(true));
Enter fullscreen mode Exit fullscreen mode

Conclusion

The speed improvements might not be so obvious on browsers, as modern computers are so powerful, but javascript does not run only on modern and powerful devices. I develop applications for smartTV-s at my current job, using HTML, CSS, JS, the performance impact it had on the old model of TV-s is subsectional. I had to make changes to a library we were using to implement this behavior, the results were good for me and I thought to share it with others.

Thank You!

PS: this is my first blog post :P

Latest comments (2)

Collapse
 
bgrand_ch profile image
Benjamin Grand

Thanks!

Collapse
 
rubinelezi profile image
Rubin Elezi

You're welcome 😊