MediumSquare
Technology

What Your Browser Does in the 16 Milliseconds You Never Think About

A plain-language tour of the frame: style, layout, paint and composite, and why the order matters.

26

Sixty frames per second sounds like a gamer's concern. For a web page it means the browser has roughly 16 milliseconds to turn your code into pixels, over and over, while the user scrolls and taps. Most of us never look inside that window. Once I did, a lot of 'mysterious' jank stopped being mysterious.

The stages of a frame

In a simplified view, every frame can involve these steps:

  1. JavaScript runs: event handlers, timers, animation callbacks.
  2. Style is recalculated: which CSS rules apply to which elements.
  3. Layout works out geometry: where everything sits and how big it is.
  4. Paint fills in pixels: text, colours, borders, shadows.
  5. Composite stacks painted layers and sends them to the screen.

The browser is smart about skipping steps. Change only transform or opacity on an element that has its own layer, and it can often jump straight to compositing. Change width, and it has to redo layout, then paint, then composite.

Photo by Ales Nesetril on Unsplash
Photo by Ales Nesetril on Unsplash

The bug that taught me this

We had a sticky header that shrank as you scrolled. It stuttered on every laptop in the office except mine. The scroll handler read offsetHeight on the header, then set a new height, then read offsetTop on the content below.

Each read after a write forced the browser to calculate layout immediately, mid-script, so it could answer honestly. Three forced layouts per scroll event, dozens of events per second. On my fast machine it squeaked under the budget. Everywhere else it did not.

The fix had two parts:

  • Read every measurement first, then write every change. Never interleave.
  • Animate the shrink with transform: scaleY() instead of height, so layout was not involved at all.

A mental model that helps

I now picture the frame as a kitchen during dinner service. JavaScript takes the orders. Style and layout are prep. Paint is cooking. Compositing is plating. If you keep running back to ask the prep cook for a measurement while they are mid-chop, everything slows down. Batch your questions.

Tools worth five minutes

  • The Performance panel in DevTools shows each frame as a coloured strip. Purple is layout; long purple bars are a clue.
  • 'Paint flashing' highlights areas being repainted. If the whole page flashes when one counter changes, something is wrong.

You do not need to memorise rendering engine internals. You just need to remember the order of the kitchen, and to stop interrupting the cooks.

Cover: Photo by Pankaj Patel on Unsplash.

26
5 people clapped
Written byMatteo Rossi

Frontend developer in Milan. Browsers, performance and the web platform.

More to read