Minimizing DOM Access

Accessing the Document Object Model (DOM), which corresponds to your HTML structure, can be burdensome for your application because frequent DOM access impacts performance. It can be compared to fetching each individual ingredient from the kitchen while cooking. Gathering all the ingredients at once is decidedly more efficient. Similarly, fetching the DOM once and keeping it for future use, a method we refer to as caching, is a more effective approach.

Suppose we are working with a paragraph. Let's say we are building a story, and we need to add a sentence to that paragraph ten times. An intuitive approach would be:

for (let i = 0; i < 10; i++) {
    document.getElementById('myPara').innerText += ' This is sentence number: ' + i;
}

In the above lines of code, we are visiting the DOM ten times to fetch the same paragraph each time, similar to fetching a new ingredient from the kitchen each time. So, how can we increase efficiency? How about we visit the DOM just once, acquire what we need, and use it repeatedly? We'll stick to our cooking analogy for clarity—fetch all the ingredients we need once and store them close to us while we are cooking.

A more efficient method might look like this:

var myPara = document.getElementById('myPara');
for (let i = 0; i < 10; i++) {
    myPara.innerText += ' This is sentence number: ' + i;
}

In this case, we accessed the DOM only once to fetch the paragraph, stored it in a variable called myPara, and used this variable within our loop. Isn't that more efficient?

Batch DOM Changes

When we make many changes to the DOM, the browser has to recalculate the page's layout and refresh the view after each change, which can take a considerable amount of time. This process is known as reflow.

Just like an efficient chef gathers all the ingredients first before starting to cook to save time, we can make our DOM manipulations faster by batching changes. Batching means making all the changes at once, triggering only a single reflow.

You might be wondering how we can batch DOM changes. The trick lies in using a DocumentFragment.

A DocumentFragment is a minimal version of a Document object, and it doesn’t carry the entire baggage of a full-fledged HTML document. It is like a lightweight container for storing DOM nodes. The magic of DocumentFragment is that when we make changes to it, these changes do not cause reflow. It’s only when the DocumentFragment is appended back to the actual DOM that a reflow happens. The fragment is created using the document.createDocumentFragment method.

For instance, suppose we want to add 5 new li elements to our ul. Instead of directly appending each li to the ul, we create a DocumentFragment, append our new li elements to the DocumentFragment, and then append the entire DocumentFragment to the ul, all at once! This triggers just one reflow, improving performance.

Here’s how it looks:

var fragment = document.createDocumentFragment(); // create a document fragment

for (let i = 1; i <= 5; i++) {
    var newElement = document.createElement('li'); // create a new li
    newElement.innerHTML = 'Item ' + i; // set the content
    fragment.appendChild(newElement); // append the li to the fragment
}

document.getElementById('myList').appendChild(fragment); // append the fragment to the ul

So, by using DocumentFragment to batch DOM changes, we can keep our applications running smoothly even when making a lot of changes to the DOM. Happy coding!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal