What makes a page janky: reflow and repaint
An animation stutters or a click takes a visible moment, and the profiler blames "Layout", not your JavaScript. Layout is not slow because the page is big; it is slow because your code makes the browser do it many times. Here is which changes re-run layout, how far one change spreads, and how reading a size in the middle of writing turns one layout into a thousand.
01 A loop that takes 100 ms
A list of cards should each grow by a pixel. The code is short and obviously linear:
With 1,000 cards this took about 110 ms in a recent Chrome on a Mac laptop, every time. Reading all the heights first and then writing them took under 4 ms. Same changes, same final page. The difference is how many times the browser had to lay out the page, and that is decided by the order of your reads and writes.
If the stages of rendering (style, layout, paint, composite) are new to you, read The DOM, layout and paint first; this page goes inside the layout stage.
02 Layout is lazy until you ask
Browsers do not lay out the page each time you change a style. A write only marks the affected boxes as needing layout. The real work happens once, just before the next frame is drawn, and covers every change made since the last one.
That is also why a single change can cost more than the one box you touched. Here is a width change on one card, as Blink (Chrome’s engine) typically handles it. Gecko and WebKit use similar dirty flags.
- needs layout
- flagged or moved
- laid out now
- clean
A clean page: body holds main and footer; main holds two cards; card 1 holds a title and a paragraph.
Blink keeps a layout cache: a box whose inputs, such as its available width, are unchanged can keep its last result and just be moved. Newer engines lean on this heavily, but anything that changes a width tends to spread downwards through the subtree, and anything that changes a height spreads upwards and onwards.
03 Which properties re-run layout
A property re-runs layout if it can change a box’s size or position, or the size or position of anything around it. The rest only repaint, and two common ones can skip paint as well.
| Change | Layout | Paint | Composite |
|---|---|---|---|
| width, height, min-/max-width | yes | yes | yes |
| margin, padding, border-width | yes | yes | yes |
| top, left, right, bottom (positioned) | yes | yes | yes |
| font-size, font-family, line-height, font-weight | yes | yes | yes |
| display, position, float, flex and grid properties | yes | yes | yes |
| text content, adding or removing elements | yes | yes | yes |
| color, background, box-shadow, outline, border-color | no | yes | yes |
| visibility | no | yes | yes |
| transform, opacity (on a composited layer) | no | no | yes |
A class change costs whatever the properties it changes cost. Toggling a class that only changes color is a repaint; one that also changes padding is a layout. Engines differ in details, and the exact cost of a property can change between versions, so measure when it matters.
04 Reads that force layout now
Some APIs return geometry: sizes, positions, scroll offsets. If the layout is dirty when you call one, the browser cannot answer from stale numbers, so it runs style and layout immediately, inside your script. This is a forced synchronous layout, or forced reflow.
| API | Examples |
|---|---|
| Element box metrics | offsetWidth, offsetHeight, offsetTop, offsetLeft, offsetParent |
| Client and scroll metrics | clientWidth, clientHeight, scrollWidth, scrollHeight, scrollTop |
| Rectangles | getBoundingClientRect(), getClientRects() |
| Computed style of layout values | getComputedStyle(el).width, .height, .top |
| Text that depends on layout | el.innerText |
| Actions that need positions | el.focus(), el.scrollIntoView(), document.elementFromPoint() |
A read on its own is not the problem. If the layout is clean, the answer is already stored and costs almost nothing. The problem is a read after a write, inside the same task.
05 Reading layout mid-write
Here is the loop from the first section on three cards, followed by the fixed version.
- just happened
- forced layout
- layout dirty
- not visited yet
The previous frame left the layout clean: every box has a known size. The loop is about to visit three cards.
- just happened
- layout dirty
- answered from cache
Same three cards, same clean layout. This time the code reads every height first and writes afterwards.
This is layout thrashing. The total work grows with the number of items times the cost of one layout, and one layout itself grows with the page. That is why it hides in small tests and appears with real data.
06 How to see it yourself
In Chrome DevTools, open the Performance panel, record while you trigger the code, and look inside your script’s task. Each forced layout is a purple Layout block under the function that read the size, and DevTools marks it with a warning about a forced reflow. A healthy frame has one Layout block, after the script.
For a number, time both versions. This is the script behind the figures in the first section; the results come from one machine and will differ on yours, but the ratio is what matters:
07 Keeping layouts few and small
for (const c of cards) {c.style.height =(c.offsetHeight + 1) + 'px';}
const hs = cards.map((c) => c.offsetHeight);requestAnimationFrame(() => {cards.forEach((c, i) => {c.style.height = (hs[i] + 1) + 'px';});});
- Batch reads before writes. When code from different places shares a page, a common pattern is to queue writes and run them in
requestAnimationFrame, so they happen together just before the frame. - Animate `transform` and `opacity`. Moving a box with
transform: translateY()does not change its layout box, so neighbours are not laid out again. - Let the browser tell you.
ResizeObserverandIntersectionObserverreport sizes and visibility after layout has run, instead of you pollingoffsetHeightin a scroll handler. - Limit how far a change spreads.
contain: layouttells the browser that nothing inside an element affects layout outside it, andcontent-visibility: autoskips layout for off-screen sections until they are near the viewport.
08 When reflow bites
window.addEventListener('scroll', () => {
bar.style.width = window.scrollY / max * 100 + '%';
label.textContent = el.getBoundingClientRect().top;
});Writes and reads in a scroll handlerA scroll event can fire many times per frame, and each write-then-read pair forces a layout. Read first, write in requestAnimationFrame, or use an observer.@keyframes grow { to { height: 300px; } }Animating a layout propertyAnimating height, top or margin re-runs layout on every frame, often for everything below it. Animate transform: scale() or translate() instead, or use a single-frame change.el.classList.add('open');
const h = el.scrollHeight;Measuring right after a class changeThe class may change layout properties, so the next geometry read forces layout. It is fine once; inside a loop over many elements it is thrashing.<img src="photo.jpg">Images with no sizeUntil the image loads the browser does not know its height, so the content below jumps when it does. Give width and height attributes (or aspect-ratio) so the box is right from the first layout.const w = getComputedStyle(el).width;Hidden reads in helpersLibrary calls such as "get outer height" or "is visible" often read geometry under the hood. Profile before assuming a loop only writes.