Lesson 9 of 12 · 10 min · How the browser works
Rendering, reflow and repaint
What you will learn
- The steps the browser repeats for every visual change: style, layout, paint, composite
- What causes reflow (layout) and repaint
- Avoid layout thrashing when reading and writing the DOM
- Animate with
transformandopacity, and userequestAnimationFrame - Profile slow rendering in DevTools
In simple words
Every time something on the page changes, such as a menu opening, an image loading or a number updating, the browser has to work out the page again: which styles apply, where everything goes, what colour each pixel is, and then show it. Some changes are cheap, like changing a colour. Others make the browser re-measure the whole page, like changing the width of a box. If your code triggers expensive work again and again, the page stutters. This lesson shows what is cheap, what is expensive and why.
Words to know
- Reflow (layout): the browser recalculating the size and position of elements.
- Repaint: the browser redrawing pixels for elements that changed appearance.
- Compositing: combining drawn layers into the final image on screen.
- Jank: visible stuttering when the browser cannot produce frames fast enough.
The rendering pipeline
After the DOM and CSSOM exist, each frame the browser may run:
- Style: work out which CSS rules apply to each element (computed styles).
- Layout (reflow): compute the geometry: width, height and position of every box.
- Paint: fill in pixels: colours, text, borders, shadows, images, into one or more layers.
- Composite: combine layers (often on the GPU) in the right order to produce the frame.
A screen at 60 frames per second has about 16 milliseconds per frame (8 ms at 120 Hz), and some of that belongs to the browser. If your JavaScript, style, layout and paint together take longer, frames are dropped and the page janks. On a low-end phone the budget is the same but the processor is much slower.
What triggers what
Changing a CSS property can start the pipeline at different points. The earlier the starting step, the more work follows:
| Change | Triggers | Cost |
|---|---|---|
width, height, margin, padding, top, left, font-size, display, adding or removing elements, changing text |
layout, then paint, then composite | highest |
color, background-color, box-shadow, border-radius, visibility, outline |
paint, then composite (no layout) | medium |
transform, opacity, filter (on promoted layers) |
composite only | lowest |
You can look up what each property triggers (csstriggers is a well-known reference table). Layout is the expensive step because changing one element's size can change its parents, siblings and children.
Reflow happens when geometry changes: the window is resized, content is added, an image loads without declared dimensions, fonts load and change the text size, or a script changes a size or position. A reflow of one small subtree is cheap; a reflow of the whole document on every scroll event is not. Repaint happens when appearance changes without geometry changing.
Layout thrashing
Reading a layout property (offsetHeight, offsetWidth, clientHeight, getBoundingClientRect(), scrollTop, getComputedStyle(el).width) forces the browser to compute layout right now, so the answer is accurate. If you alternate reads and writes in a loop, the browser must recalculate layout on every iteration. This is layout thrashing (forced synchronous layout):
// Bad: write, read, write, read ... forces a layout every iteration
for (const box of boxes) {
box.style.width = box.parentElement.offsetWidth / 2 + "px"; // read (forces layout) then write
}
// Good: read everything first, then write everything
const widths = boxes.map(box => box.parentElement.offsetWidth); // all reads: one layout
boxes.forEach((box, i) => { box.style.width = widths[i] / 2 + "px"; }); // all writes: one layout later
Other ways to reduce work:
- Batch DOM changes: build elements in a
DocumentFragmentor setinnerHTMLonce, then insert once, rather than inserting 1,000 nodes one at a time. - Change classes, not many inline styles, so that the browser handles the update once:
el.classList.toggle("open"). - Take elements out of the flow while editing (
display: none, edit, then show) for large changes. - Avoid very deep or huge DOMs (thousands of nodes): style and layout cost grows with size. For long lists, use virtualisation (render only visible rows; libraries such as TanStack Virtual or react-window).
- Use
content-visibility: autoon large off-screen sections so the browser skips rendering them until needed (addcontain-intrinsic-sizeto avoid layout jumps). - Avoid very expensive CSS in hot paths: large
box-shadoworfilter: blur()on big areas, and complex selectors matter little compared to layout cost, but animating them is costly.
Animate with transform and opacity
To move or fade something smoothly, change only transform and opacity, which the browser can handle on the compositor (often on the GPU), without running layout or paint on the main thread:
/* Janky: animating left forces layout every frame */
.panel { position: absolute; left: 0; transition: left 300ms; }
.panel.open { left: 200px; }
/* Smooth: transform is composite-only */
.panel { transition: transform 300ms ease; }
.panel.open { transform: translateX(200px); }
will-change: transform hints that an element will animate, so the browser promotes it to its own layer in advance; use it sparingly (each layer costs memory), preferably set just before the animation and removed after. Respect users who ask for less motion:
@media (prefers-reduced-motion: reduce) { .panel { transition: none; } }
The CSS Web Animations API and @keyframes are generally better than JavaScript timers for animation.
requestAnimationFrame
For animation or visual updates in JavaScript, use requestAnimationFrame (rAF) instead of setTimeout or setInterval. The callback runs just before the next paint, once per frame, paused in background tabs:
function tick(now) {
el.style.transform = `translateX(${Math.sin(now / 500) * 100}px)`;
requestAnimationFrame(tick);
}
requestAnimationFrame(tick);
Use rAF to batch writes (collect changes in event handlers, apply them in one frame). For scroll, resize and mousemove handlers, which fire many times a second, throttle with rAF or debounce, mark listeners { passive: true } so the browser does not wait to see whether you will cancel scrolling, and prefer IntersectionObserver (visible or not), ResizeObserver (element size changes) and CSS position: sticky to polling in scroll handlers.
Long tasks and the main thread
The main thread runs JavaScript, style, layout and paint, and handles user input. A script that runs for more than 50 ms is a long task and blocks clicks and rendering, which hurts Interaction to Next Paint (INP). Fix by:
- Splitting work into chunks and yielding to the browser (
await scheduler.yield()where available, orsetTimeout(0)). - Moving heavy computation to a Web Worker (a background thread).
- Doing less work: less JavaScript, memoisation, virtualised lists.
Images, fonts and layout shift
Content that loads late and pushes other things around causes Cumulative Layout Shift (CLS) and extra reflows:
- Give images and videos
widthandheight(oraspect-ratio) so space is reserved. - Use
font-display: swaporoptionalwith similar fallback fonts (andsize-adjust) to avoid text jumping when web fonts load. - Reserve space for ads, embeds and banners; insert new content below the viewport or in response to a user action, not above content people are reading.
Profiling
In Chrome DevTools:
- Performance panel: record while you interact. The flame chart shows Recalculate Style, Layout (purple), Paint (green), scripting (yellow), and the frames row with dropped frames. A red triangle and "Forced reflow" warnings point to layout thrashing, and a "Long task" marker shows main-thread blocking.
- Rendering tab: tick Paint flashing (areas repainted flash green), Layout Shift Regions and Frame Rendering Stats (FPS meter).
- Layers panel (More tools) shows compositor layers.
- Throttle the CPU 4x or 6x to simulate a phone, since your laptop hides problems.
- Lighthouse and the Web Vitals extension report LCP, INP and CLS.
Common mistakes
- Animating
width,height,toporleftinstead oftransform. - Alternating DOM reads and writes in loops.
- Appending nodes one by one to a large list.
- Scroll handlers doing layout reads on every event.
- Images without dimensions and late-loading fonts causing shifts.
will-changeon everything.- Profiling only on a fast machine.
Try it yourself
- Animate a box with
left, then withtransform, and compare in the Performance panel with 4x CPU throttling. - Write a loop that reads
offsetWidthand writesstyle.widthfor 500 elements, then rewrite it to batch reads and writes, and measure. - Turn on Paint flashing and scroll or hover on your page; fix one unnecessary repaint.
- Add
widthandheightto images and check the CLS in Lighthouse before and after. - Replace a scroll handler that measures elements with an
IntersectionObserver.
Check yourself
What are the stages of the browser rendering pipeline?
Style calculation, layout (reflow), paint and composite.
Which CSS properties can be animated without layout or paint?
transform and opacity, which the compositor can handle (on the GPU).
What is layout thrashing?
Alternating reads of layout properties (like offsetHeight) with writes to styles, forcing the browser to recalculate layout repeatedly; batch reads first and writes after.
Why use requestAnimationFrame for animations?
It runs the callback right before the next paint, aligned with the display refresh and paused in hidden tabs, avoiding wasted or janky frames.
Interview questions
What is the difference between reflow and repaint?
Reflow (layout) recalculates the size and position of elements when geometry changes; repaint redraws pixels when appearance changes without affecting layout. Reflow is costlier and usually triggers a repaint too.
How would you optimise a page that stutters while scrolling?
Profile with the Performance panel; remove layout reads from scroll handlers (use IntersectionObserver or passive listeners), animate with transform and opacity, reduce paint areas, virtualise long lists, break up long tasks and test with CPU throttling.
What does will-change do and what are the risks?
It hints that a property will change so the browser can prepare a layer ahead of time; overuse consumes memory and can make performance worse.
Summary
- Each frame may run style, layout, paint and composite; layout is the costliest.
- Avoid forced reflows by batching DOM reads before writes; batch inserts and prefer classes.
- Animate with
transformandopacity, userequestAnimationFrame, observers and passive listeners. - Reserve space for media and fonts, break up long tasks and profile with throttling.
Going deeper
- web.dev: Rendering performance: the pipeline and how to optimise each stage.
- web.dev: Avoid large, complex layouts and layout thrashing: reads and writes.
- MDN: Populating the page: how browsers work: parsing, layout and paint.
- MDN: requestAnimationFrame: reference.
See how much of this you can explain
A free mock interview asks you new questions on HTML, CSS and how the web works for Frontend Developer and scores every answer, with what to fix.