- Grokking the Modern Frontend System Design Interview
0% completed
How a Browser Turns HTML into Pixels
On This Page
The Steps from Bytes to Pixels
Files That Make the Browser Wait
Layout, Paint and Composite Again
Forced Synchronous Layout
Using This in an Interview
Key Takeaways
Practice Questions
How a Browser Turns HTML into Pixels <!doctype html> <html> <head> <link rel="stylesheet" href="/basket.css"> <script src="/analytics.js"></script> </head> <body> <ul class="products"> <li class="card"><img src="/apples.svg" alt="Apples"> Apples, 2.49</li> </ul> </body> </html>These twelve lines are a cut-down version of one product card on Basket, the grocery store web app used throughout this course. In the lab, the stylesheet was set to arrive after 400 ms and the analytics script after 800 ms. The card appeared at 864 ms, even though the card itself has nothing to do with analytics.
Adding one word,
defer, to the script tag moved the first content to 452 ms. The difference comes from the order in which the browser turns these lines into pixels, and from which steps are allowed to wait for which files.This page walks through that order, step by step, and shows what makes the browser repeat part of it.
The Steps from Bytes to Pixels
The browser receives the page as bytes and must do six kinds of work before the shopper sees a card. Each step uses the result of the step before it.
- Parse the HTML into the DOM. The parser reads the tags and builds a tree of objects, one per element and one per piece of text. That tree is the DOM (Document Object Model), and it is also what JavaScript reads and changes.
- Parse the CSS into the CSSOM. The browser reads every stylesheet and builds a second tree of rules, the CSSOM (CSS Object Model).
- Build the render tree. The browser combines the two trees and keeps only what will be drawn, with its final styles. An element with
display: noneis left out, and so is everything in the<head>. - Layout. The browser works out the position and size of every box in pixels, for this screen width.
- Paint. The browser records the drawing commands for each box: text, borders, colors, images.
- Composite. The browser combines the painted pieces, called layers, into the final image on the screen.
From HTML and CSS to pixels Look at where the two inputs meet: the render tree needs both the DOM and the CSSOM. Notice also that layout, paint and composite run in that order every time, so a change that forces layout also forces the two steps after it.
The parser does not wait for the whole file. It builds the DOM while the bytes are still arriving, and a separate preload scanner reads ahead in the HTML to start downloading stylesheets, scripts and images it finds, before the parser reaches them.
Files That Make the Browser Wait
Two kinds of waiting matter. A file blocks rendering when the browser will not draw anything until the file has arrived. A file blocks parsing when the parser stops building the DOM until the file has arrived and run.
A stylesheet in the
<head>blocks rendering. The browser waits for it so that the shopper does not see unstyled text that jumps into place a moment later. A plain<script>tag blocks parsing, because the script may change the page that comes after it, so the parser must run it before it reads further. A plain script also waits for the stylesheets above it to finish, because the script may ask for a style.Resource Blocks parsing Blocks rendering When the script runs <link rel="stylesheet">in the headNo Yes Not a script <script src>Yes Everything after it As soon as it arrives <script src defer>No No After parsing, in document order <script src async>Only while it runs Only while it runs As soon as it arrives, in any order <script type="module">No No After parsing, like defer<img>No No Not a script Here is the lab result for the two versions of the opening page. Both were measured in headless Chrome 150 on a desktop with an AMD Ryzen 7 5800X, with the server holding the stylesheet for 400 ms and the script for 800 ms.
Output:
opening.html: first content on screen at 864 ms (median of 5) opening-defer.html: first content on screen at 452 ms (median of 5)In the first version, the parser stopped at the script and did not reach the card until 800 ms had passed. In the second version, parsing continued, so only the 400 ms stylesheet stood between the bytes and the first paint. The rest of each result, 64 ms in the first version and 52 ms in the second, covers the HTML request and the browser's own work, which this run did not break down.
Layout, Paint and Composite Again
The first frame is not the end of this work. Any change to the page after it loads makes the browser repeat some of the steps, and which steps depends on what changed.
What the code changes Example Steps the browser repeats Size or position width,margin, font size, adding a rowLayout, paint, composite Look only color,background-color,box-shadowPaint, composite Transform or opacity on its own layer transform: translateX(...),opacityComposite only What a change costs Look at the third row. Composite is the only step that the browser can run outside the main thread, on a separate compositor thread. An animation that changes only
transformoropacityon an element with its own layer can therefore stay smooth while JavaScript keeps the main thread busy.A layer is a part of the page that the browser paints separately and keeps as its own image. The browser creates layers for some elements by itself, and
will-change: transformasks it to create one ahead of an animation. Each layer costs memory for its image, so a page with hundreds of layers can run slower than a page with a few.Forced Synchronous Layout
The browser normally waits to do layout until the next frame, so that ten style changes cost one layout. Code can break this by asking for a size or position right after a change, with properties such as
offsetHeight,getBoundingClientRect()orscrollTop. To answer, the browser must run layout at once, inside the script. This is called forced synchronous layout. When code does it in a loop, writing and reading in turn, the pattern is called layout thrashing.Here are two ways to resize 300 product cards in the lab sample and read back their heights.
// Interleaved: write one width, then read one height. Every read forces a new layout. function interleaved(width) { const heights = [] for (const card of cards) { card.style.width = width + 'px' heights.push(card.offsetHeight) } return heights } // Batched: all writes first, then all reads. The browser lays out once. function batched(width) { for (const card of cards) card.style.width = width + 'px' const heights = [] for (const card of cards) heights.push(card.offsetHeight) return heights }The same machine ran both, with the CPU slowed four times to approximate a mid-range phone:
Output:
cards: 300, CPU 4x slower write then read, one card at a time: 233.3 ms (median of 5) all writes, then all reads: 10.7 ms (median of 5)Both functions produce the same 300 heights. The first one ran layout 300 times and took about 22 times longer. At 60 frames per second, the browser has about 16.7 ms to produce each frame, the frame budget worked out in Estimating Bytes Frames and Requests. The 233 ms of the first version is therefore about 14 frames in which the screen could not change.
The repair is to group the work: make every change first, then read every value you need, or read everything before the first change.
Using This in an Interview
Say where the first paint waits: "The stylesheet blocks rendering, so I keep the CSS for the first screen small. Scripts get
defer, and animations change onlytransformandopacity." That shows you know which step each choice affects.Two follow-up questions are likely:
- "Why would reading
offsetHeightinside a loop make a page slow?" - "Which CSS properties can you animate without running layout?"
Key Takeaways
- The browser builds the DOM from HTML and the CSSOM from CSS, combines them into a render tree, then runs layout, paint and composite.
- A stylesheet in the head blocks rendering, and a plain script blocks parsing;
deferandtype="module"let parsing continue. In the lab this moved first content from 864 ms to 452 ms. - A size or position change repeats layout, paint and composite; a color change repeats paint and composite; a
transformoropacitychange on its own layer repeats only composite. - Composite can run on the compositor thread, so animations of
transformandopacitystay smooth while the main thread is busy. - Reading a size right after a change forces layout inside the script. Writing and reading in turn for 300 cards took 233.3 ms, against 10.7 ms when all reads came after all writes.
Every one of these steps, except composite, runs on the same main thread as the page's JavaScript. The next lesson, The Main Thread and Long Tasks, shows how the browser shares that thread between scripts, clicks and frames.
Practice Questions
Try each question first, then open the answer.
1. A page has one stylesheet in the head that takes 300 ms to arrive and an async analytics script that takes 900 ms. When can the first content appear, and which file decides it?
<details> <summary>Show answer</summary>At about 300 ms, decided by the stylesheet. The stylesheet blocks rendering, so nothing is drawn before it arrives. An async script does not stop the parser while it downloads, so it does not delay the first paint. It runs whenever it arrives, which here is after the first paint.
</details>2. An element is hidden with
<details> <summary>Show answer</summary>display: none, and another withvisibility: hidden. Which one is in the render tree, and why does that matter for layout?Only the
</details>visibility: hiddenelement is in the render tree. It is not drawn, but it still takes up space, so layout must place it and the boxes around it move to make room for it. Thedisplay: noneelement is left out, so it takes no space and costs no layout.3. A product carousel slides by changing each slide's
<details> <summary>Show answer</summary>leftproperty 60 times a second. A teammate proposestransform: translateX()instead. What changes for the browser?Each frame needs only composite instead of layout, paint and composite. Changing
</details>leftchanges position, so every frame repeats layout and paint on the main thread. Atransformon an element with its own layer is applied by the compositor, so the slide can stay smooth even when JavaScript is busy.4. A function sets the height of 500 rows and, after each one, reads
<details> <summary>Show answer</summary>getBoundingClientRect()of that row. What is the problem, and what is the repair?Each read forces a new layout, so the function runs layout about 500 times. This is layout thrashing. The repair is to make all 500 changes first and then read all 500 sizes, so the browser lays out once. In the lab, the same change for 300 cards went from 233.3 ms to 10.7 ms.
</details>5. Why does the browser wait for a stylesheet before drawing anything, instead of drawing plain text and styling it later?
<details> <summary>Show answer</summary>Drawing first would show unstyled content that changes size and position when the styles arrive. Every box would be laid out twice, and the shopper would see the page jump. Waiting costs time on the first paint, which is why the stylesheet needed for the first screen should be small and arrive early.
</details>Reading Progress
0%
On This Page
The Steps from Bytes to Pixels
Files That Make the Browser Wait
Layout, Paint and Composite Again
Forced Synchronous Layout
Using This in an Interview
Key Takeaways
Practice Questions