Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 8.8 — DOM Performance
JavaScript · Example 2 of 2

Forced layout and the read-then-write fix

Both versions give the same result. The first forces a fresh layout on each turn after a write (3 bars here, thousands on a real list); the second needs only one. Reading offsetWidth returned 60 straight after the write, which proves the browser laid out on the spot.

Every DOM change can make the browser recalculate styles, redo layout (reflow) and redraw pixels (repaint); the browser batches this work until the next frame, so the way to stay fast is to batch your changes too, build big pieces off-page with a DocumentFragment, and never alternate layout reads with writes (layout thrashing).

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Rewrite this loop so it never forces more than one layout: for (const el of items) { el.style.height = el.offsetHeight + 20 + "px"; }. Log the new heights for three 40px items.

02

Write renderNames(list, names) that replaces the contents of list with one <li> per name using a single insertion, and log how many <li> the list has after rendering ["Asha", "Ravi", "Meera"] twice.

Explain it without notes

01

What are reflow and repaint, and which kinds of change trigger each?

02

What is layout thrashing, and how do you fix it?

03

Why are ten style changes in a row usually not ten times as expensive as one?

04

How would you add 5,000 rows to a table efficiently?

Forced layout and the read-then-write fix

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

60
[ 100, 160, 240 ]
[ 100, 160, 240 ]