What is a Batch DOM update and Why is it useful?

jharna_khatun

Jharna Khatun

Posted on October 18, 2024

What is a Batch DOM update and Why is it useful?

Batching DOM updates :

Batching DOM updates refers to making multiple changes to the DOM in a way that reduces the number of reflows and repaints, which are costly operations for the browser. A Batch DOM update is when you make multiple changes to a webpage's structure (the DOM) all at once, instead of one by one.

Why is it useful?

Making changes to the DOM one at a time can slow down your webpage because the browser has to keep stopping, recalculating positions, and redrawing the page for every single change. By batching updates, you combine all the changes and apply them in one go, making your webpage faster and smoother.

Scenario:

Imagine you’re moving furniture around a room. If you move one chair, then wait for everyone to notice, then move a table, and wait again, it will take forever. But if you move everything at once and show the final result, the process will be quicker and less disruptive.

In coding terms, instead of updating the DOM every time you add or change something, you collect all your changes and apply them together, which is much faster.

Example:

Instead of adding items to a list one by one (slow):

// Updating DOM one by one (slow)
const list = document.getElementById('myList');
const newItem = document.createElement('li');
newItem.textContent = "Item 1";
list.appendChild(newItem);
Enter fullscreen mode Exit fullscreen mode

You can collect all the items in a "batch" and add them all at once (fast):

// Batch DOM update (fast)
const list = document.getElementById('myList');
const fragment = document.createDocumentFragment();

for (let i = 1; i <= 5; i++) {
    const newItem = document.createElement('li');
    newItem.textContent = `Item ${i}`;
    fragment.appendChild(newItem);
}

list.appendChild(fragment);

Enter fullscreen mode Exit fullscreen mode

This way, the browser only updates the page once after all the items are ready, making it faster and more efficient!

💖 💪 🙅 🚩
jharna_khatun
Jharna Khatun

Posted on October 18, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related