Courses / Frontend System Design, with JavaScript Foundations / Chapter 7
Module 3 · Browser Foundations · Chapter 7 of 21
How the Browser Loads and Renders a Page
Builds on Promises, Async Code and the Browser Event Loop and The DOM, Events and Observers. Next up: Machine Coding Practice in Plain JavaScript.
Part 1 · From URL to first byte
Before the first request
A page is slow for one of two reasons: the browser waits for the network, or it works too hard once the bytes arrive. Every measurement below comes from Chrome 157 on this machine.
When you open a URL, the browser cannot send the request yet. It first needs an address, then a connection. Each step costs at least one round trip, the time for a message to reach the server and for the reply to come back. The usual name for that time is round-trip time (RTT).
The steps run in order. DNS lookup turns the host name into an IP address, and the result is usually cached after the first time. A TCP handshake then opens the connection with three messages, SYN, SYN-ACK and ACK. For an https address, a TLS handshake follows, agreeing on encryption and checking the server's certificate. Per MDN, once DNS is done, a new connection with a full TLS handshake takes two round trips with TLS 1.3 and three with TLS 1.2 before the request can be sent.
You can turn those counts into time by choosing an RTT. The numbers below use 40 ms as an assumed round trip, chosen only to make the arithmetic easy to follow, and a server that answers instantly. They are arithmetic, not a measurement.
const rtt = 40 const rows = [ ['http, new connection', 1], ['https, TLS 1.3', 2], ['https, TLS 1.2', 3], ] console.log('assumed round trip:', rtt, 'ms; server waits 0 ms') for (const [label, trips] of rows) { const beforeRequest = trips * rtt const firstByte = beforeRequest + rtt console.log(label.padEnd(22), 'before request', beforeRequest + ' ms, first byte at least', firstByte, 'ms') }
assumed round trip: 40 ms; server waits 0 ms http, new connection before request 40 ms, first byte at least 80 ms https, TLS 1.3 before request 80 ms, first byte at least 120 ms https, TLS 1.2 before request 120 ms, first byte at least 160 ms
Output (Node 24)
Even with an instant server, an https page on TLS 1.3 cannot show its first byte before 120 ms, and TLS 1.2 adds another 40 ms. Round trips are paid before any server code runs, and they grow with distance, which is why the connection setup is the first thing worth removing.
Reading TTFB in Chrome
Time to First Byte (TTFB) is the time between starting a navigation and receiving the first byte of the HTML response. It includes any redirects, DNS, connection setup, the request, the server's own work and the trip back.
The browser records these moments in the Navigation Timing API. performance.getEntriesByType('navigation')[0] returns an entry with fields such as domainLookupStart and domainLookupEnd for DNS, connectStart and connectEnd for TCP and TLS, requestStart when the request went out, and responseStart when the first byte arrived. Subtracting pairs gives the phases.
This script runs a local server that waits before answering, loads the page in Chrome and reads the entry for three waits. Everything is on loopback, so the network phases should be close to zero and the server wait should dominate.
import { createServer } from 'node:http' import { open } from './harness.mjs' const server = createServer((req, res) => { const url = new URL(req.url, 'http://x') const think = Number(url.searchParams.get('think')) setTimeout(() => { res.setHeader('content-type', 'text/html') res.end('<!doctype html><title>t</title><p>hello</p>') }, think) }) await new Promise((ok) => server.listen(55810, '127.0.0.1', ok)) const { browser, page } = await open() for (const think of [0, 150, 400]) { await page.goto(`http://localhost:55810/?think=${think}`) const t = await page.evaluate(() => { const n = performance.getEntriesByType('navigation')[0] return { dns: n.domainLookupEnd - n.domainLookupStart, connect: n.connectEnd - n.connectStart, ttfb: n.responseStart - n.startTime, } }) const f = (v) => String(Math.round(v)).padStart(4) console.log(`server waits ${think} ms:`.padEnd(22), 'dns', f(t.dns), 'connect', f(t.connect), 'ttfb', f(t.ttfb), '(ms)') } await browser.close() server.close()
server waits 0 ms: dns 0 connect 0 ttfb 5 (ms) server waits 150 ms: dns 0 connect 0 ttfb 161 (ms) server waits 400 ms: dns 0 connect 0 ttfb 403 (ms)
Output (Chrome 157)
DNS and connection time were 0 because localhost needs no lookup and a loopback connection is instant. TTFB followed the server wait: 5 ms for an instant answer, then 161 ms and 403 ms for waits of 150 and 400. The few extra milliseconds are the request, the response headers and process overhead on this machine, and they vary from run to run. On a real network each of the earlier phases would add its own bar, and the field values would come from users, not from a lab run. The performance chapter covers measuring in the field.
Shortening the path
There are two ways to cut time before the first byte: do fewer round trips, or make each one shorter. Serving from a CDN, a network of servers near the users, shortens each one. Reusing an open connection for later requests to the same origin avoids repeating the handshakes. HTTP caching avoids the request altogether when the content is still fresh.
For a connection you know you will need, you can start the handshake early. A <link rel="preconnect"> hint tells the browser to open a connection to another origin now, before the page asks for anything from it. Per MDN, preconnect does DNS and TCP for an http origin and adds TLS for an https one, and it brings no benefit for same-origin requests because that connection is already open. MDN also warns that preconnecting to many origins can hurt, so keep it for the few that matter. For a less critical origin, rel="dns-prefetch" does only the DNS step.
There is no run for preconnect in this chapter, so its description rests on MDN. The saving it aims at is the handshake round trips from the table on the first page.
MDN also gives a rule for the first response: the first chunk the server sends is usually about 14 KB, so the HTML and CSS needed to start drawing should fit in it where possible. The reason is TCP slow start: a new connection begins with a small congestion window, the amount of data the server may send before it waits for an acknowledgement, and the window roughly doubles each round trip. Bytes beyond the first flight wait at least one more round trip. That is a guideline for early rendering, not a limit on page size. The API chapter covers how HTTP/2 and HTTP/3 change the connection costs.
After DNS, how many round trips does a new https connection need before the request can be sent?
- Two with TLS 1.3 and three with TLS 1.2, per MDN. One of those is the TCP handshake.
In the loopback run, why did TTFB track the server's wait?
- DNS and connection time were both 0 on
localhost, so almost all the time to the first byte was the server holding its answer.
Part 2 · Parsing and script loading
Two trees
The browser does not wait for the whole HTML file. As bytes arrive, the HTML parser turns them into the DOM tree, one node at a time, so the top of a long page can be ready while the rest is still downloading. CSS goes through its own parser into the CSS Object Model (CSSOM), a second tree that holds every rule.
Neither tree can be drawn alone. The browser combines them into a render tree of the elements that will be shown, each with its computed styles. Per MDN, elements such as <head> and anything with display: none are left out, and an element with visibility: hidden is kept because it still takes up space.
While the parser works, a helper called the preload scanner reads ahead in the HTML and starts downloads for scripts, stylesheets and images it spots, so they do not wait for the parser to reach them. The rest of this lesson is about when the parser and the render tree have to stop and wait, and for what.
| Step | Input | Output |
|---|---|---|
| Parse HTML | bytes of the document | DOM tree |
| Parse CSS | stylesheets and style attributes | CSSOM tree |
| Combine | DOM and CSSOM | render tree with computed styles |
| Layout, paint, composite | render tree | pixels on screen |
CSS blocks rendering
A stylesheet that applies to the screen is render-blocking: the browser will not paint until it has it, because painting with half the styles would flash unstyled content. Per MDN, waiting for CSS does not stop HTML from being parsed or downloaded, but it does stop JavaScript, because a script may ask for a style and needs the real answer.
The test serves a page with an inline script and a paragraph. A stylesheet link arrives 600 ms late in the first case. In the second, the same file is linked with media="print", which does not apply to the screen. The page records when its script ran, and Chrome reports the time of the first paint.
import { listen, siteHandler } from './servers.mjs' import { open } from './harness.mjs' const server = await listen(siteHandler, 55810) const { browser, page } = await open() const base = 'http://localhost:55810/css-page/' await page.goto(base + 'print?warmup') const cases = [['all', 'stylesheet, 600 ms late'], ['print', 'same file, media=print']] for (const [media, label] of cases) { await page.goto(base + media) const t = await page.evaluate(() => new Promise((done) => { new PerformanceObserver((list) => { const hit = list.getEntries() .find((e) => e.name === 'first-contentful-paint') if (!hit) return done({ script: window.ranAt, paint: Math.round(hit.startTime) }) }).observe({ type: 'paint', buffered: true }) })) console.log(label.padEnd(25), 'script ran at', String(t.script).padStart(4), 'ms, first paint', String(t.paint).padStart(4), 'ms') } await browser.close() server.close()
stylesheet, 600 ms late script ran at 618 ms, first paint 624 ms same file, media=print script ran at 18 ms, first paint 28 ms
Output (Chrome 157)
With the late stylesheet the inline script that came after the link did not run until 618 ms, and the first paint followed at 624 ms. With the non-matching media query both happened within 30 ms. These are lab numbers from one machine and they vary from run to run, but the gap of about 600 ms is the stylesheet delay.
The practical rules follow. Keep the CSS needed for the first screen small and early. Do not put a script after a slow stylesheet if the script does not need styles. Load stylesheets that are only needed for print, or for later parts of the page, with a media query that does not match the screen, so they do not hold up the first paint.
Classic, async, defer and module scripts
A classic script with no attributes is fetched and executed as soon as the parser reaches it, and the parser stops until that is done. That is parser-blocking. The slower the file, the longer the page below it stays unbuilt. The attributes async and defer, and type="module", avoid the stop, and they differ in when the code runs.
| Script | Fetch | Runs | Order |
|---|---|---|---|
| classic | parser waits for it | immediately | document order |
async | in parallel with parsing | as soon as it arrives | not guaranteed |
defer | in parallel with parsing | after parsing, before DOMContentLoaded | document order |
type="module" | in parallel, deferred by default | like defer | document order |
Fetchparser waits for it
Runsimmediately
Orderdocument order
asyncFetchin parallel with parsing
Runs
Part 3 · Style, layout, paint and composite
Four stages after parsing
Once the DOM and CSSOM exist, the browser turns them into pixels in stages. Style matches the CSS rules to each element and computes its final values. Layout works out the size and position of every box. Paint records what to draw, such as text, borders and backgrounds, and fills in the pixels. Composite stacks the painted layers in the right order and sends the result to the screen.
The stages run in this order, each using the result of the one before. A change to the page restarts the pipeline at the earliest stage it affects and runs everything after it. Changing the size of an element needs layout, because neighbours may move, and then paint and composite. Changing only a colour skips layout. A change that the compositor can apply to an existing layer, such as moving that layer, can skip both layout and paint.
Watch for how far each kind of change travels down the pipeline
Read it as steps
Each kind of change restarts the pipeline at a different stage.
The scene is the model. The next page checks it against a real trace from Chrome, and the answer is less tidy than the model, which is the reason to measure.
What a change reaches
Chrome can record a trace of its own work. The script loads two 100 pixel boxes, one of them with will-change: transform, makes one change at a time, waits for two frames and counts the trace events for each stage. The names in the trace are the engine's own: UpdateLayoutTree is the style stage, Layout and Paint are as named, and RasterTask is the work of drawing a layer's pixels.
const categories = ['devtools.timeline', 'cc'] const STAGES = { UpdateLayoutTree: 'style', Layout: 'layout', Paint: 'paint', RasterTask: 'raster' } async function trace(label, change) { await browser.startTracing(page, { categories }) await page.evaluate(change) await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)))) await page.waitForTimeout(150) const buf = await browser.stopTracing() const events = JSON.parse(buf.toString()).traceEvents const n = (name) => events.filter((e) => e.name === name).length const counts = Object.entries(STAGES) .map(([event, name]) => name + ' ' + n(event)) console.log(label.padEnd(24), counts.join(', ')) } await trace('width', () => { a.style.width = '200px' }) await trace('background colour', () => { a.style.background = 'orange' }) await trace('transform', () => { a.style.transform = 'translateX(40px)' }) await trace('transform, will-change', () => { lifted.style.transform = 'translateX(40px)' })
The tracing helper and the four changes.
width style 1, layout 1, paint 2, raster 1 background colour style 1, layout 0, paint 2, raster 1 transform style 1, layout 1, paint 2, raster 1 transform, will-change style 1, layout 0, paint 0, raster 0
Output (Chrome 157)
The width change went through style, layout, paint and raster. The colour change skipped layout. The transform on an ordinary element still ran layout in this build, which the simple model would not predict. Only the box that had will-change: transform ran no layout, no paint and no raster after the style step: the browser moved an existing layer.
Treat the trace as the authority. Which properties skip which stages depends on the engine and its version, and on whether the element sits on its own layer. The reliable method is the one used here: change one thing, record, and read the stages. The DevTools Performance panel records the same work, and its Main track shows events such as Recalculate Style, Layout and Paint.
Layers and their price
A layer is a separate surface the compositor can move, fade or scale without asking the page to redraw. The browser decides which elements get one, and CSS properties such as will-change: transform are a request to promote an element. The benefit is the last row of the trace: animation that costs almost nothing per frame.
The price is memory and bookkeeping. Each layer needs its own backing store, and the compositor has more to track. MDN states that excessive use of will-change results in excessive memory use and more complex rendering, and calls it a last resort for an existing performance problem, not something to add in advance. The last lesson of this chapter counts the layers a page of promoted tiles creates.
For now the model to keep is this. For things that move often, prefer changes that skip layout, and confirm it in a trace. Measure before promoting, promote only what animates, and remove the hint when the animation ends.
Which stage can a colour change skip, according to the trace?
- Layout. The trace showed one style pass, two paint events and a raster task, but zero layout passes.
Why is it unsafe to assume that transform never triggers layout?
- The trace for a plain element with a transform still showed a layout pass in this Chrome build. Which stages run depends on the engine, its version and whether the element has its own layer.
What does promoting an element to its own layer cost?
- Memory for its own backing store and extra work for the compositor, which is why
will-changeshould be used sparingly and only for things that animate.
Part 4 · Layout thrashing
Forced synchronous layout
Browsers avoid doing layout more than once a frame. When a script changes a style, the browser marks layout as out of date and waits. At the next rendering opportunity, covered in the event loop chapter, it brings style and layout up to date once for all the changes. Batching is what keeps frames cheap.
Reading a geometry value breaks that batching. If you change a style and then read offsetWidth, offsetHeight, getBoundingClientRect() or scrollTop, the browser cannot answer from a stale layout. It must finish the layout right now, in the middle of your script, and then answer. Per web.dev this is called forced synchronous layout, or forced reflow, and it is unnecessary and potentially expensive work when the script could have waited.
One forced layout is usually fine. The problem is doing them in a loop, which web.dev calls layout thrashing. A loop that writes a style on each item and then reads the next item's width forces a layout on every pass after the first. Each read depends on the write before it, so the browser can never combine the work.
Which reads force layout is a long list and depends on the browser. The dependable way to find them is to record a trace in the DevTools Performance panel and read its "Forced reflow" insight, or to count Layout events in a trace, as the next page does.
Measuring the thrash
The test builds 300 boxes of different widths and applies a 4x CPU throttle in Chrome, so the timings are larger than on a fast machine. They are lab numbers from this machine and vary. Two versions grow every box by 10 pixels. The first reads and writes in the same loop. The second reads every width first, then writes every width.
for (const name of ['thrash', 'batched']) { await browser.startTracing(page, { categories: ['devtools.timeline'], }) const scriptMs = await page.evaluate(async (name) => { const els = [...document.querySelectorAll('.card')] const t = performance.now() if (name === 'thrash') { for (const el of els) el.style.width = el.offsetWidth + 10 + 'px' } else { const widths = els.map((el) => el.offsetWidth) els.forEach((el, i) => { el.style.width = widths[i] + 10 + 'px' }) } const took = performance.now() - t await new Promise((r) => requestAnimationFrame(() => { requestAnimationFrame(r) })) return Math.round(took) }, name) const raw = (await browser.stopTracing()).toString() const layouts = JSON.parse(raw).traceEvents .filter((e) => e.name === 'Layout' && e.ph === 'X') const layoutMs = layouts.reduce((sum, e) => sum + e.dur, 0) / 1000 console.log(name.padEnd(8), 'script', String(scriptMs).padStart(4), 'ms, layout passes', layouts.length + ', layout total', Math.round(layoutMs), 'ms') }
thrash script 137 ms, layout passes 300, layout total 105 ms batched script 1 ms, layout passes 1, layout total 4 ms
Output (Chrome 157)
The thrashing version made 300 layout passes and spent about 105 ms in layout inside a script that took 137 ms. The batched version made one layout pass, in the rendering step after the script, and its script itself took about 1 ms. Because the second version ran second on an already modified page, the sizes differ a little between the two, but the pass counts are what matter: one per iteration against one in total.
A second run marked the start and end of the loop with console.timeStamp and sorted the layout events by time. The first read found layout up to date, so 299 passes were forced inside the script and the last write was laid out in the rendering step.
thrash total 300 inside script 299 after 1 before 0 batched total 1 inside script 0 after 1 before 0
Output (Chrome 157, 4x CPU throttling, loop start and end marked)
Fixing it
The fix is an ordering rule: read first, then write. Collect every measurement you need into variables, then apply every change. The batched version in the test is that rule. If the reads depend on earlier writes, restructure so they do not, for example by computing sizes from your own data instead of asking the DOM.
A few habits follow. Do not mix reading and writing inside one loop. When updates come from events such as scrolling, record the new values in the handler and apply them in a requestAnimationFrame callback, so all writes happen at the start of a frame. Prefer APIs that deliver geometry without forcing it: IntersectionObserver and ResizeObserver, from the previous chapter, report values computed during rendering, so reading them does not force a layout.
Finally, remember what the measurement does and does not show. A thrashing loop over 300 boxes cost about 137 ms of script at 4x throttling. On a real mid-range phone the multiplier can be larger, and a frame has about 16 ms at 60 frames a second. The count of layout passes is the number to watch, and the rendering budget is the reason.
Why does reading offsetWidth right after a style write force layout?
- The browser has marked layout out of date. To return a correct width it must finish the layout immediately instead of waiting for the next frame.
How did the batched version reduce 300 layout passes to one?
- It read every width before changing any style, so layout stayed valid during the reads. All the writes then shared one layout in the rendering step.
Why are ResizeObserver and IntersectionObserver safer than measuring in a loop?
- They deliver sizes and positions that were computed during rendering, so reading them does not make the browser run layout in the middle of your script.
Part 5 · Skipping work
content-visibility
The cheapest layout is the one the browser never does. Pages with long lists, feeds or articles contain much content that is far below the screen and will not be seen for seconds or ever. The CSS property content-visibility: auto tells the browser it may skip the rendering work for an element while that element is off screen, and do it when it nears the viewport.
Per MDN, auto turns on layout, style and paint containment for the element, and skips its contents while it is not relevant to the user. MDN lists it as Baseline 2024, newly available, working in the latest browsers since September 2024. The skipped content stays in the DOM and the accessibility tree, so find in page, tab order and screen readers still work, unlike display: none.
The test inserts 1,500 sections of 12 paragraphs each, at 4x CPU throttling, with and without the property, and times the work until the second animation frame. The plain variant has no rule. The other sets content-visibility: auto and contain-intrinsic-size: auto 400px.
for (const [name, css] of Object.entries(variants)) { await page.setContent('<body></body>') await browser.startTracing(page, { categories: ['devtools.timeline'], }) const out = await page.evaluate(async ([css, body]) => { const t = performance.now() document.head.insertAdjacentHTML('beforeend', `<style>${css}</style>`) document.body.innerHTML = body await new Promise((r) => requestAnimationFrame(() => { requestAnimationFrame(r) })) return { ms: Math.round(performance.now() - t), height: document.documentElement.scrollHeight, } }, [css, body]) const raw = (await browser.stopTracing()).toString() const layout = JSON.parse(raw).traceEvents .filter((e) => e.name === 'Layout' && e.ph === 'X') .reduce((s, e) => s + e.dur, 0) / 1000 console.log(name) console.log(' second frame after', out.ms, 'ms, layout', Math.round(layout), 'ms') console.log(' page height', out.height, 'px') }
The loop that runs both variants; the second sets the property with a 400 pixel stand-in.
plain second frame after 921 ms, layout 611 ms page height 688223 px content-visibility second frame after 152 ms, layout 10 ms page height 600390 px
Output (Chrome 157)
The plain page spent 611 ms in layout and took 921 ms to reach its second frame. With content-visibility: auto the same page spent 10 ms in layout and reached it in 152 ms. They are lab numbers on this machine and vary, but the order of magnitude is the point: layout cost follows what is visible, not what exists.
Intrinsic size and the scrollbar
Skipped content has no layout, so the browser does not know its height. Without a stand-in, every skipped section would collapse to nothing, and the scrollbar would jump as sections came into view and grew. The property contain-intrinsic-size supplies the stand-in. The test used auto 400px: the auto keyword means use the last real size once the element has been rendered, and 400 pixels until then.
The page height in the last run shows the stand-in at work. With everything laid out, the page was 6,88,223 pixels tall. With 1,500 skipped sections at 400 pixels each, it measured 6,00,390, because the estimate was too small for these sections, which are about 459 pixels tall. As the reader scrolls, each rendered section remembers its true size, and the scrollbar thumb shifts. A closer estimate means fewer visible shifts.
The rule is to give a stand-in near the real height. Measure a typical section, round it, and use that. Use it on items whose content is below the first screen, not on the sections that contain the largest contentful paint, which would delay the very thing you want early.
Containment and will-change
content-visibility works by switching on containment, a promise that an element's inside does not affect the outside. You can make the promise yourself with the contain property, which MDN lists as widely available since March 2022. contain: layout isolates the element's internal layout from the rest of the page. contain: paint stops descendants displaying outside its box. contain: size makes the element's size independent of its contents. contain: content is shorthand for layout, paint and style, and strict adds size.
With a promise like that the browser can redo layout inside a widget, such as a chat bubble or a card in a list, without re-checking the whole page. Containment is safe for components whose size is set by their container, and risky when content is meant to overflow, since paint containment clips it.
The memory cost of promotion from the lesson on layers can be counted. The last script lays out 200 tiles, once plain and once with will-change: transform, and asks Chrome's layer tree how many layers exist.
import { open } from './harness.mjs' const { browser, context, page } = await open() const cdp = await context.newCDPSession(page) await cdp.send('LayerTree.enable') let layers = [] cdp.on('LayerTree.layerTreeDidChange', (e) => { layers = e.layers ?? [] }) const tiles = (css) => `<style> .t { width: 120px; height: 120px; margin: 4px; display: inline-block; background: teal; ${css} } </style>${'<div class="t"></div>'.repeat(200)}` for (const [label, css] of [['no hint', ''], ['will-change: transform', 'will-change: transform']]) { layers = [] await page.setContent(tiles(css)) await page.waitForTimeout(500) const area = layers.reduce((s, l) => s + l.width * l.height, 0) console.log(label.padEnd(24), 'layers', layers.length, 'total layer area', Math.round(area / 1e6 * 10) / 10, 'M pixels') }
no hint layers 4 total layer area 5.6 M pixels will-change: transform layers 204 total layer area 8.5 M pixels
Output (Chrome 157)
Without the hint, the page had 4 layers. With it, 204: one for each tile plus the four the page had anyway. Every one is a separate surface with its own backing memory, and the compositor has to track all of them. The hint is worth that cost for the one element that is animating now, and a poor trade for a list of 200.