Optimizing DOM Mutations

Optimizing DOM Mutations

Do you do DOM mutations? In the right way?
Let's discuss different approaches and the right way to do DOM mutations in JS.

First of all, let's discuss a term called DocumentFragment.
The DocumentFragment interface represents a minimal document object that has no parent.
It is used as a lightweight version of Document that stores a segment of a document structure comprised of nodes just like a standard document.

Let's now see different approaches to DOM mutations:

Approach 1 (Strongly advised not to follow):

    for (int i = 0; i < 10000; i++) {
        const p = document.createElement("p");
        document.body.appendChild(p);
    }

The above approach takes 413.125ms

Approach 2 (Best way to follow):

    const fragment = new document.createDocumentFragment();
    for (int i = 0; i < 10000; i++) {
        const p = document.createElement("p");
        fragment.appendChild(p);
    }
    document.body.appendChild(fragment);

The above approach takes 12.189ms

Explanation:

This huge performance difference is due to the fact that the document fragment isn't part of the active document tree structure. Thus, changes made to the fragment don't affect the document (even on reflow) or incur any performance impact when changes are made.
Also, render is triggered each time an element is added to the DOM. So in the first approach, render is triggered 10000 times whereas in the second approach it is triggered only once in the end.

Pro Tip: Once the fragment is appended to the document body, the fragment becomes empty. This is because the appendChild method moves all the nodes to DOM and leaves the DocumentFragment empty
This means no duplication of nodes and helps in optimized space usage as well.

Hope you have learned something new. If yes, share it with your friends and colleagues.

Let's meet at the other tech article next time. Until then stay connected with me on LinkedIn

-- Pasumarthi Sai Phani Krishna (aka PSPK)๐Ÿ˜Š

Knowledge credits:
Code snippet and time analysis are taken from one of Akshay Saini's posts. DocumentFragment definition and details are learned from MDN docs.