Part 01 · How the Browser Works

Lab: Reading a Performance Trace

DevToolsPerformance panelNetwork throttlingLighthouse

Record a trace of ShopLite on a throttled CPU and network, and learn to read the main thread, the network waterfall and a Lighthouse report.

⏱ 12 min · Station 10 of 125

What you'll be able to do

Take any slow ShopLite page and answer three questions with evidence instead of guesses:

  1. Where did the main thread's time go? Scripting, rendering or painting, and which long tasks blocked input.
  2. What did the network do, and in what order? The waterfall: which requests waited for which.
  3. What does Lighthouse say, and why can its numbers disagree with your trace?

You'll do it twice: by hand in Chrome DevTools, and with tools/profile.mjs and tools/lighthouse.sh, which print the same information as text (and save a trace you can open in DevTools).

Set up the recording

Start the lab from Lab Setup: ShopLite (docker compose up -d --wait). Then, by hand:

  1. Open Chrome in a guest or incognito window (extensions add their own scripts to every trace) and go to http://localhost:5173/products.
  2. Open DevTools (F12) and the Performance panel.
  3. In the panel's capture settings (the gear icon), set CPU: 4x slowdown and Network: Slow 4G. These are the conditions a mid-range phone on mobile data sees.
  4. Click Record and reload. DevTools reloads the page, records until it settles, and shows the trace.
  5. For Lighthouse, open the Lighthouse panel, choose Mobile and Performance, and click Analyze page load.

The scripts do the same from the command line. tools/profile.mjs loads the page with the slow4g profile from lib.mjs (562.5 ms per request, 1.47 Mbps, CPU 4x), records a trace, writes it to trace.json, and prints a summary:

// node profile.mjs [path]: record a performance trace of a ShopLite page on "slow 4G + 4x CPU"
// and print what DevTools' Performance panel would show: the summary, the long tasks, the network.
import { writeFileSync } from "node:fs";
import { open, trace, pageTimings, resources, waterfall, WEB, ms } from "./lib.mjs";

const path = process.argv[2] ?? "/products";
const { browser, page } = await open({ profile: "slow4g" });
const events = await trace(browser, page, async () => {
  await page.goto(WEB + path, { waitUntil: "networkidle" });
});
const t = await pageTimings(page);
const res = await resources(page);
await browser.close();
writeFileSync("trace.json", JSON.stringify({ traceEvents: events })); // open this file in DevTools

const main = events.find((e) => e.name === "thread_name" && e.args?.name === "CrRendererMain");
const mine = events.filter((e) => e.pid === main.pid && e.tid === main.tid && e.ph === "X");
const sum = (names) => mine.filter((e) => names.includes(e.name)).reduce((s, e) => s + e.dur / 1000, 0);
const groups = {
  "Loading (parse HTML)": ["ParseHTML"],
  "Scripting": ["EvaluateScript", "v8.compile", "FunctionCall", "TimerFire", "EventDispatch", "RunMicrotasks", "v8.evaluateModule"],
  "Rendering (style + layout)": ["UpdateLayoutTree", "Layout", "PrePaint"],
  "Painting": ["Paint", "Layerize", "Commit"],
};
console.log(`${WEB}${path} on slow 4G + 4x CPU\n`);
console.log("Summary (main thread)");
for (const [k, names] of Object.entries(groups)) console.log(`  ${k.padEnd(28)} ${ms(sum(names)).padStart(7)}`);

const tasks = mine.filter((e) => e.name === "RunTask" && e.dur > 50_000).sort((a, b) => b.dur - a.dur);
const t0 = Math.min(...mine.map((e) => e.ts));
console.log(`\nLong tasks (> 50 ms): ${tasks.length}`);
for (const lt of tasks.slice(0, 5)) {
  const inside = mine.filter((e) => e.ts >= lt.ts && e.ts < lt.ts + lt.dur && e !== lt && e.name !== "RunTask");
  const top = inside.sort((a, b) => b.dur - a.dur)[0];
  console.log(`  ${ms(lt.dur / 1000).padStart(7)} at ~${ms((lt.ts - t0) / 1000).padStart(7)}  mostly: ${top?.name}${top?.args?.data?.url ? " " + top.args.data.url.replace(/^.*\//, "") : ""}`);
}
console.log(`\nTimings: FCP ${ms(t.fcp)}  LCP ${ms(t.lcp)}  DOMContentLoaded ${ms(t.dcl)}  load ${ms(t.load)}`);
console.log("\nNetwork waterfall");
const rows = [{ label: "document", start: 0, end: t.responseEnd }, ...res.map((r) => ({ label: r.name.split("?")[0], start: r.start, end: r.end }))];
console.log(waterfall(rows.slice(0, 12)));
if (rows.length > 12) console.log(`  ... and ${rows.length - 12} more image requests`);

tools/lighthouse.sh runs the Lighthouse CLI (installed with tools/) in mobile mode and prints the key numbers from its JSON report:

# Lighthouse on the ShopLite listing page, mobile preset (simulated slow 4G, 4x CPU).
npx lighthouse http://localhost:5173/products --quiet --only-categories=performance \
  --chrome-flags="--headless=new --no-sandbox" --output=json --output-path=lh.json >/dev/null 2>&1
node -e '
const r = require("./lh.json");
const a = r.audits;
console.log("Performance score:", Math.round(r.categories.performance.score * 100));
for (const k of ["first-contentful-paint", "largest-contentful-paint", "total-blocking-time", "cumulative-layout-shift", "speed-index"])
  console.log(" ", a[k].title.padEnd(26), a[k].displayValue);
console.log("Top opportunities:");
Object.values(a).filter((x) => x.details?.type === "opportunity" && x.score !== null && x.score < 1)
  .sort((x, y) => (y.details.overallSavingsMs ?? 0) - (x.details.overallSavingsMs ?? 0)).slice(0, 3)
  .forEach((x) => console.log("  -", x.title, x.displayValue ? "(" + x.displayValue + ")" : ""));
'

Record it

Measured on an Intel i3-10110U laptop (4 threads), 7 GB RAM, Ubuntu 26.04, Chrome 151 headless via Playwright 1.64.1 (window 1280 x 800), Lighthouse 13.6.0, the lab in Docker on the same machine.

The trace:

cd ../lab/tools && node profile.mjs /products
http://localhost:5173/products on slow 4G + 4x CPU

Summary (main thread)
  Loading (parse HTML)            8 ms
  Scripting                     194 ms
  Rendering (style + layout)    110 ms
  Painting                       87 ms

Long tasks (> 50 ms): 2
    75 ms at ~1511 ms  mostly: v8.evaluateModule
    69 ms at ~2341 ms  mostly: RunMicrotasks

Timings: FCP 1652 ms  LCP 3588 ms  DOMContentLoaded 1580 ms  load 1580 ms

Network waterfall
document                   |#######                                 |    0 ms ->  576 ms
/assets/index-C1s9lTqF.js  |       ##########                       |  596 ms -> 1497 ms
/assets/index-DwuM_Ger.css |       ######                           |  597 ms -> 1174 ms
/api/products              |                  ########              | 1620 ms -> 2300 ms
/favicon.ico               |                  #######               | 1623 ms -> 2198 ms
/img/1.svg                 |                           #######      | 2374 ms -> 2953 ms
/img/2.svg                 |                           #######      | 2374 ms -> 2960 ms
/img/3.svg                 |                           #######      | 2374 ms -> 2968 ms
/img/5.svg                 |                           #######      | 2374 ms -> 2976 ms
/img/4.svg                 |                           #######      | 2374 ms -> 2984 ms
/img/6.svg                 |                           #######      | 2375 ms -> 2992 ms
/img/7.svg                 |                           #############| 2378 ms -> 3524 ms
  ... and 25 more image requests

The Lighthouse run:

cd ../lab/tools && CHROME_PATH=/usr/bin/google-chrome sh lighthouse.sh
Performance score: 100
  First Contentful Paint     0.8 s
  Largest Contentful Paint   1.8 s
  Total Blocking Time        0 ms
  Cumulative Layout Shift    0
  Speed Index                0.8 s
Top opportunities:
  - Reduce unused JavaScript (Est savings of 28 KiB)

To look at the same trace in DevTools: Performance panel, Load profile, pick tools/trace.json.

Reading the trace

The Summary (DevTools: the Summary tab at the bottom, with nothing selected) splits main-thread time by kind:

CategoryTimeWhat it is on this page
Scripting194 msrunning the React bundle, the API callback, React rendering 60 cards
Rendering (style + layout)110 msstyling and laying out the grid, mostly after the cards arrive
Painting87 msdrawing cards and images
Loading (parse HTML)8 msthe HTML is almost empty

Under 400 ms of main-thread work in total. On this page the CPU is not the problem.

Long tasks (DevTools: the tasks marked with red stripes in the Main track): two, of 75 ms and 69 ms.

  • The 75 ms one at about 1.5 s is v8.evaluateModule: the browser running the JS bundle right after it downloads. Every client-rendered page pays this; bigger bundles pay more (Part 7).
  • The 69 ms one at about 2.3 s is the API response turning into pixels. Opening it up in the trace: 23 ms of RunMicrotasks (the fetch promise callbacks and the React update they trigger), then 21 ms of layout plus style, pre-paint and paint for the 60 new cards.
  • A tap during either would wait up to 70 ms. Fine for now; a 10,000-product list would not be (see Parsing HTML and CSS).

The network waterfall (DevTools: the Network track, or the Network panel) is where the time actually goes:

  • document 0-576 ms, then the JS and CSS 596-1497 ms, then /api/products 1620-2300 ms, then images from 2374 ms. Four waves again, the same pattern as The Life of a Page Load, and each wave pays the 562 ms latency.
  • /img/7.svg ends at 3524 ms, about 550 ms after images 1-6: the 6-connections-per-host limit of HTTP/1.1.

The timings: FCP 1652 ms, LCP 3588 ms. In this 1280 px window the largest element is a product image, so LCP waits for the images, the last wave.

Lighthouse says 100, with FCP 0.8 s and LCP 1.8 s. Why so different?

  • Simulated vs applied throttling. Lighthouse's default (throttlingMethod: simulate) loads the page at full speed, then estimates how it would load on slow 4G with a model of connections and round trips. Our trace applied the throttling to every request. Same profile numbers, different method, different results.
  • A different viewport. Lighthouse mobile uses a 412 px phone screen, where the largest element is the "Products (10000)" heading, not an image. A different LCP element means a different LCP.
  • The score is relative. 100 means "fast compared to the thresholds", not "nothing to improve". The waterfall above still shows four sequential waves.

The rule: compare numbers only when they were measured the same way. Use Lighthouse to track a page over time and for its suggestions ("Reduce unused JavaScript", 28 KiB here), and traces to understand why.

When the recording looks wrong

  • Lots of chrome-extension:// scripts in the trace: extensions run in the page. Use a guest or incognito window.
  • The trace shows the dev server (hundreds of small .tsx requests): you opened Vite's dev server. The lab serves the production build on 5173; measure that.
  • Numbers jump between runs: a laptop on battery, other apps, thermal throttling. Run 3-5 times and take the median, like crp.mjs does.
  • Lighthouse can't start Chrome: set CHROME_PATH to your Chrome binary, as lighthouse.sh is run in the walkthrough.
  • DevTools "Slow 4G" doesn't match slow4g: DevTools' built-in presets have changed between Chrome versions. Use a custom profile with 562.5 ms latency, 1474 kbps down, 675 kbps up, or use the scripts.

Key takeaway

A trace tells you where the main thread spent its time, which long tasks blocked input, and how the requests chained. Lighthouse gives a quick, comparable score from a simulation. Read the waterfall first, the long tasks second, and only compare numbers measured the same way.

Station stamp

Finish the chapter

Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +15 XP.

Go Pro to earn XP →