Understanding how browsers update what you see on screen
Before we dive into repaint and reflow, let's understand the browser's Critical Rendering Path - the sequence of steps browsers take to convert HTML, CSS, and JavaScript into pixels on screen.
Repaint and reflow occur when the browser needs to update what's displayed on screen after the initial render.
Reflow (also called layout) occurs when the browser must recalculate the position and geometry of elements in the document.
This happens when changes affect the layout of the page, such as:
Reflow is expensive because it often triggers child and ancestor elements to reflow as well (known as layout thrashing).
// JavaScript triggering reflow:
reflowBox.style.width = '150px';
reflowBox.style.height = '80px';
Repaint occurs when the browser needs to redraw pixels to the screen when elements change visually, but their geometry remains the same.
This happens with changes like:
Repaint is generally less expensive than reflow since it doesn't require recalculating element positions, but frequent repaints can still impact performance.
// JavaScript triggering repaint:
repaintBox.style.backgroundColor = '#f87171';
repaintBox.style.opacity = '0.7';
This is the general order of operations with associated costs
Because reflow may require recalculating positions of many elements
Properties like transform and opacity can skip layout and paint
Click both buttons rapidly to see the performance difference