Efficient DOM Manipulation — Performance

Writing to the DOM only marks the layout stale, and the browser computes it once when it draws. Reading a size (offsetHeight, getBoundingClientRect()) after a…

The chart on a dashboard has only 100 bars, yet every time its data updates, your phone stutters for a moment. The code is just a short loop: read a bar's height, write the new height. What makes it heavy isn't the number of bars, it's the order of the reads and writes.

The DOM is the tree of page elements the browser keeps, which JavaScript can read and change. Every time an element's size or content changes, the browser has to recompute the layout, the position and size of every box on the page, before it draws. Efficient DOM manipulation means making that recomputing happen as rarely as possible. Picture rearranging the furniture in a room while someone keeps asking "how wide is the walkway now?". If after moving each wardrobe you have to measure the whole room again, you wear yourself out. Cheaper: measure everything once, write it down, then move all the furniture.

Reading and writing the DOM

Code that touches the DOM does two different things:

If you read while the layout is stale, the browser is forced to compute the layout right then, in the middle of your JavaScript. This is called a forced synchronous layout. Reads and writes that alternate again and again, forcing a layout every time, are called layout thrashing.

Read everything first, then write everything

Take three bars with heights of 5, 10 and 3 px. Each height should become height * 2 + 10, so the result is 20, 30 and 16 px. The page is calm, so the layout starts out fresh.

Step Alternating Batch
1 read bar 1 (layout fresh) read bar 1
2 write bar 1, layout stale read bar 2
3 read bar 2: layout forced read bar 3
4 write bar 2, layout stale write bar 1
5 read bar 3: layout forced write bar 2
6 write bar 3 write bar 3
Forced layouts 2 0

After the loop, both need one more layout when the next frame is drawn. With 100 boxes, the alternating version forces the layout 99 times, plus 1 time in the next frame: 100 in total. The batch version needs just 1. A hundred against one, only because of the order.

// Alternating: every read after a write forces a layout
const bars = [...document.querySelectorAll(".bar")]; // heights 5, 10, 3

bars.forEach((bar) => {
  const h = bar.offsetHeight;           // read
  bar.style.height = h * 2 + 10 + "px"; // write
});
// Batch: read everything first, then write everything
const bars = [...document.querySelectorAll(".bar")];

const heights = bars.map((bar) => bar.offsetHeight); // [5, 10, 3]
bars.forEach((bar, i) => {
  bar.style.height = heights[i] * 2 + 10 + "px";     // 20, 30, 16
});

The exercise models this pattern without a DOM: each element becomes an object { value }.

function batchUpdate(elements) {
  const values = elements.map((element) => element.value);   // 1. read everything
  return values.map((value) => ({ value: value * 2 + 10 }));  // 2. write everything
}

console.log(batchUpdate([{ value: 5 }, { value: 10 }, { value: 3 }]));
// [{ value: 20 }, { value: 30 }, { value: 16 }]

Adding many elements at once

Adding 1,000 <li> one by one to a list on the page does not cause 1,000 layouts, as long as nothing in the loop reads a size. The layout is still put off until the next frame. But every element that enters the page still adds a little work: the browser records the change and marks the styles that need recomputing. A DocumentFragment is a light container that lives in memory, not on the page. Collect every element in it, then put it into the page once.

const list = document.querySelector("#list");
const fragment = document.createDocumentFragment(); // a container in memory

for (let i = 1; i <= 1000; i++) {
  const li = document.createElement("li");
  li.textContent = "Item " + i;
  fragment.appendChild(li); // the page hasn't changed yet
}

list.appendChild(fragment); // 1,000 <li> go in at once

textContent or innerHTML

The rule: data from a user always goes through textContent.

⚠️ DOM code that looks safe but isn't

TL;DR: Writing to the DOM only marks the layout stale, and the browser computes it once when it draws. Reading a size (offsetHeight, getBoundingClientRect()) after a write forces a layout right then, and alternating reads and writes in a loop is called layout thrashing: 100 boxes become 100 layouts. Read everything first, then write everything, and the layout happens only once. For many new elements, collect them in a DocumentFragment and put it in once. Text from a user goes through textContent, not innerHTML. In the exercise, batchUpdate reads every value, then returns a new array of { value: value * 2 + 10 }.

⚡ Writes mark, reads force

Guess first: why can many DOM operations inside a loop slow a page down?

Not because every DOM operation triggers a reflow right away. A write only marks the layout stale, and the layout is computed when the next frame is drawn. But reading a size after a write forces a layout right then, and 100 boxes that alternate become 100 layouts.

Meaning: A write only marks the layout stale. Reading offsetHeight or getBoundingClientRect() needs a fresh layout. Reads and writes that alternate in a loop are called layout thrashing.

⚡ Read everything first, then write everything

Write:

const values = elements.map((element) => element.value);   // 1. read everything
return values.map((value) => ({ value: value * 2 + 10 }));  // 2. write everything

Meaning: Only the order changes, and the layout happens once. batchUpdate must return a new array, not just print it.

⚡ Many elements, one entry

Meaning: Collect new elements in a DocumentFragment, then put it into the page once. Text from a user always goes through textContent, not innerHTML, so it can't become XSS.

What you will learn