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:

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:

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.

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