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:
- Write: change something that affects how the page looks, such as
el.style.height = "20px",el.classList.add("big"), or adding an element. The browser doesn't compute the layout right away. It only marks "the layout is stale" and waits until it's time to draw the next frame. - Read a size or position:
offsetHeight,offsetWidth,offsetTop,clientWidth,scrollTop,getBoundingClientRect()orgetComputedStyle(). To give a correct answer, the browser needs a fresh layout.
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
});
[...document.querySelectorAll(".bar")]turns the NodeList into a plain array, somapcan be used.bars.map((bar) => bar.offsetHeight)reads every height while the layout is still fresh. There's no write in between, so no layout is forced.- The second loop only writes. The browser marks the layout stale, then computes it once when it draws.
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 }]
- The first
mapcollects only the numbers:[5, 10, 3]. - The second
mapmakes a new array of new objects.({ value: ... })is wrapped in parentheses so the curly braces are read as an object, not as a function body. batchUpdate([{ value: 0 }])gives[{ value: 10 }], because 0 times 2 plus 10 is 10.
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
- During the loop, the page isn't touched at all.
list.appendChild(fragment)moves every child of the fragment into the list. The fragment itself doesn't go in, and it is empty afterwards.- Another way that does the same: collect the elements in an array, then
list.append(...items).
textContent or innerHTML
el.textContent = textputs the text in as it is. No HTML is processed, so it's fast, and<b>shows up as the characters<b>.el.innerHTML = textprocesses that string as HTML. Handy for putting in lots of markup at once, but dangerous when the content comes from a user: a name like<img src=x onerror="...">will run its script. This hole is called XSS.
The rule: data from a user always goes through textContent.
⚠️ DOM code that looks safe but isn't
- Reading a size inside a loop that writes. It often hides in a helper function that calls
getBoundingClientRect()orgetComputedStyle(). Collect every read before the loop that writes. - Thinking every
appendChildcauses a layout right away. What's expensive is reading a size in between additions. A DocumentFragment is still useful because the page only changes once. innerHTMLwith data from a user. UsetextContent.- In the exercise: forgetting
returnor usingforEach.forEachreturns nothing.batchUpdatemust return a new array[{ value: 20 }, { value: 30 }, { value: 16 }], not just print it.
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.