Lab: Record and Read a Page-Load Trace
Set up a page with three planted performance problems, read its load in the Network and Performance panels, capture the same numbers with a small script, fix the problems and measure the difference.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: the provided slow page
- Step 2: measure the load from the command line
- Step 3: read the same load in the Network panel
- Step 4: record a trace in the Performance panel
- Step 5: fix the three problems
- Step 6: measure again and compare
- Check your understanding
- Apply it
- Review prompt
Lessons of How Browsers Render Pages
- From URL to Pixels: The Rendering Pipeline Concept · 25 min
- What Blocks the First Paint and How to Unblock It Worked example · 20 min
- The Main Thread, Long Tasks and Layout Thrashing Concept · 20 min
- Lab: Record and Read a Page-Load Trace Lab · 30 min
- Check: Annotate a Waterfall and a Flame Chart Knowledge check · 8 questions
What you will learn
- Trace a page load from navigation request to first paint: HTML parsing, DOM and CSSOM construction, style, layout, paint and compositing.
- Identify render-blocking and parser-blocking resources and remove the blocking with defer, async or type=module scripts and non-critical CSS loading.
- Capture a page-load trace with the DevTools Network and Performance panels and point to the step that dominates it.
01. Goal and setup
This lab turns the two DevTools panels you have read about — Network and Performance — into a workflow you can repeat on any page: record a load, name the step that dominates it, fix that step, and prove the improvement with before-and-after numbers. The provided page has three planted problems from the previous lessons: a render-blocking script, a render-blocking stylesheet that never matches the screen, and one task that both burns the main thread and forces hundreds of layouts. You will find all three, fix them, and report first contentful paint and a total-blocking-time estimate before and after — the same evidence the skill's practice task asks for.
You need: Node.js 22 or later with npm, and a Chromium browser. Versions verified while writing this lab: Node 22.23.2, Playwright 1.64.1 (its own Chromium build, 156.0.8078.4). No other dependencies. The lab folder:
rendering-lab/
├── server.js tiny server with adjustable delays (step 1)
├── theme.css the page's real stylesheet (fast)
├── print.css print-only rules, missing its media attribute
├── analytics.js pretend third-party tag (slow response)
├── app.js the page script, with the problems (step 1)
├── slow.html the page as provided (step 1)
├── measure.js load-time summary script (step 2)
├── fixed.html your fixed copy (step 5)
└── app-fixed.js the fixed page script (step 5)Create the folder, install Playwright, and fetch its Chromium build. If you have used Playwright on this machine before, the browser is already cached and both commands finish in seconds; otherwise the second one downloads about 150 MB once. (If you already have Google Chrome installed, you can skip the download: change chromium.launch() in step 2 to chromium.launch({ channel: 'chrome' }).)
mkdir rendering-lab && cd rendering-lab
npm install [email protected]
npx playwright install chromiumadded 2 packages in 35s02. Step 1: the provided slow page
The server serves every file in the folder and accepts a ?ms=<n> query that delays one response, so single resources can be made slow without touching the others:
// server.js — a tiny server with adjustable delays, for this lab.
// Run: node server.js (then open http://127.0.0.1:8080/slow.html)
const http = require('node:http');
const { readFileSync } = require('node:fs');
const { join } = require('node:path');
const PORT = 8080;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const types = { '.html': 'text/html', '.css': 'text/css', '.js': 'text/javascript' };
const server = http.createServer(async (req, res) => {
const url = new URL(req.url, `http://127.0.0.1:${PORT}`);
const name = url.pathname === '/' ? 'index.html' : url.pathname.slice(1);
try {
const body = readFileSync(join(__dirname, name));
const ms = Number(url.searchParams.get('ms') ?? 0);
if (ms > 0) await sleep(ms);
const type = types[name.slice(name.lastIndexOf('.'))] ?? 'text/plain';
res.writeHead(200, { 'Content-Type': type });
res.end(body);
} catch {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('not found');
}
});
server.listen(PORT, '127.0.0.1', () => {
console.log(`Serving ${__dirname} at http://127.0.0.1:${PORT}/`);
});Create the stylesheet, the print sheet, the tag and the page itself:
body { font-family: system-ui, sans-serif; margin: 1.5rem; }
#cards { display: flex; flex-wrap: wrap; gap: 0.75rem; }
.card { border: 1px solid #bbb; border-radius: 6px;
padding: 0.75rem; background: #f8fafc; }
h1 { font-size: 1.5rem; }@media print {
header, footer, nav { display: none; }
.card { border: 1px solid #000; }
}// pretend third-party analytics; its response is delayed.
window.__analyticsLoaded = true;<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="data:,">
<title>Foggy Weather (before)</title>
<link rel="stylesheet" href="/theme.css">
<script src="/analytics.js?ms=600"></script>
<link rel="stylesheet" href="/print.css?ms=900">
</head>
<body>
<h1>Foggy Weather</h1>
<p>A five-day forecast for the harbour town of Point Fang.</p>
<div id="cards"></div>
<script>
const cards = document.getElementById('cards');
for (let i = 0; i < 300; i += 1) {
const card = document.createElement('div');
card.className = 'card';
card.textContent = 'Mon 8° Tue 9° Wed 9° Thu 10° Fri 11°';
cards.appendChild(card);
}
</script>
<script src="/app.js"></script>
</body>
</html>// app.js — the page's script. Three performance problems live here.
function busy(ms) {
const start = performance.now();
while (performance.now() - start < ms) {
// stand-in for real work: sorting and reducing forecast data
}
}
function fitCards() {
const cards = document.querySelectorAll('.card');
for (const card of cards) {
const parentWidth = card.parentElement.offsetWidth; // read
card.style.width = parentWidth / 3 - 12 + 'px'; // write
}
}
window.addEventListener('load', () => {
busy(220); // one long task: the loop and every layout inside it
fitCards();
});node server.js & # keep it running; stop it later with: kill %1Serving /home/you/rendering-lab at http://127.0.0.1:8080/curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:8080/slow.html20003. Step 2: measure the load from the command line
DevTools reads its numbers from the browser's instrumentation; a script can read the same entries through Playwright. Create measure.js — you will reuse it unchanged after the fixes:
// measure.js — load a page and print its load-time summary, like a
// mini Network and Performance panel. Run: node measure.js slow.html
const { chromium } = require('playwright');
const PAGE = process.argv[2];
if (!PAGE) {
console.error('usage: node measure.js <page.html>');
process.exit(2);
}
// Runs inside the page after load and gathers the entries DevTools shows.
const collector = async () => {
const round = (x) => Math.round(x);
const nav = performance.getEntriesByType('navigation')[0];
const fcp = performance.getEntriesByName('first-contentful-paint')[0];
const resources = performance.getEntriesByType('resource').map((e) => ({
file: e.name.replace(location.origin, ''),
ms: round(e.responseEnd - e.startTime),
blocking: e.renderBlockingStatus,
}));
const longTasks = await new Promise((resolve) => {
const seen = [];
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
seen.push({ at: round(entry.startTime), ms: round(entry.duration) });
}
});
observer.observe({ type: 'longtask', buffered: true });
setTimeout(() => { observer.disconnect(); resolve(seen); }, 100);
});
const tbt = longTasks.reduce((sum, t) => sum + Math.max(0, t.ms - 50), 0);
return {
path: location.pathname,
ttfbMs: round(nav.responseStart - nav.startTime),
fcpMs: fcp ? round(fcp.startTime) : null,
loadMs: round(nav.loadEventEnd - nav.startTime),
longTasks,
tbtEstimateMs: round(tbt),
resources,
};
};
function print(report) {
const line = (label, value) => console.log(`${label.padEnd(24)}${value}`);
line('page', report.path);
line('time to first byte', `${report.ttfbMs} ms`);
line('first contentful paint', report.fcpMs === null ? 'none' : `${report.fcpMs} ms`);
line('load event', `${report.loadMs} ms`);
const tasks = `${report.longTasks.length} — ${JSON.stringify(report.longTasks)}`;
line('long tasks (>50 ms)', tasks);
line('total blocking time*', `${report.tbtEstimateMs} ms`);
console.log('resources (download ms, render-blocking status)');
for (const r of report.resources) {
console.log(` ${String(r.ms).padStart(5)} ms ${r.blocking.padEnd(12)} ${r.file}`);
}
console.log('* estimate: long-task time above the 50 ms threshold');
}
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(`http://127.0.0.1:8080/${PAGE}`, { waitUntil: 'load' });
await page.waitForTimeout(700); // let post-load work and reports settle
print(await page.evaluate(collector));
await browser.close();
})();node measure.js slow.htmlpage /slow.html
time to first byte 2 ms
first contentful paint 952 ms
load event 1267 ms
long tasks (>50 ms) 1 — [{"at":935,"ms":332}]
total blocking time* 282 ms
resources (download ms, render-blocking status)
8 ms blocking /theme.css
609 ms blocking /analytics.js?ms=600
909 ms blocking /print.css?ms=900
9 ms non-blocking /app.js
* estimate: long-task time above the 50 ms thresholdKeep this output — it is the before picture. Read it against the pipeline: the first paint came at 952 ms, after two resources the screen never needed had held it; one task of 332 ms started at 935 ms and blocked the interface for a third of a second; and the total-blocking-time estimate says 282 of those milliseconds were pure excess above the 50 ms budget.
04. Step 3: read the same load in the Network panel
Open http://127.0.0.1:8080/slow.html in your browser, press F12, and go to the Network panel. Tick Disable cache, reload, and read the waterfall top to bottom:
- The document row is short — its Waiting for server response segment is the time to first byte that measure.js printed.
analytics.jsandprint.cssshow long bars, roughly 600 and 900 ms. Hovering a row shows the full timing breakdown of that request.- The two long bars delay first paint: because both are marked render-blocking, the browser cannot paint until they finish (as
measure.jsshowed). In the Network panel, the vertical lines mark milestones — blue forDOMContentLoadedand red for theloadevent. After step 5 the same two network downloads will still take time, but first contentful paint (visible in the Performance panel timings andmeasure.js) will no longer wait for them.
The Network panel answers which request dominates; it cannot tell you what the page did with the time afterwards. That is the Performance panel's job.
05. Step 4: record a trace in the Performance panel
Switch to the Performance panel, press the record button, reload the page with the reload button inside the panel (the panel records while the page loads), stop the recording after the load settles, and let it analyse. What you should find in the recording of slow.html:
- A summary at the top shows where the time went in each category.
- On the Main thread track, one task around the 935 ms mark carries a red corner marker — the long-task flag. Its width matches the roughly 330 ms that measure.js reported.
- Open that task (click the triangle): a wide bar for
busy, then a wide bar forfitCards, and beneath it a long series of purple Layout events — one forced synchronous layout per card, the layout thrashing from the previous lesson. - The Bottom-Up tab ranks self time by function;
busyand the layout work should top it.
As a cross-check, the browser's own counters for the same load on our machine (Chromium's LayoutCount and RecalcStyleCount, read through the DevTools protocol) reported 302 layouts and 304 style recalculations for slow.html — against 2 layouts and 5 recalculations after the fix. The panel is showing you the same story as the numbers; now go and change the story.
06. Step 5: fix the three problems
Copy slow.html to fixed.html and change its head. The analytics tag is independent, so it gets async; the print stylesheet only matters on paper, so it gets media="print"; the application script needs the DOM, so app-fixed.js is loaded from the head with defer. In the body, remove the old <script src="/app.js"></script> tag at the end (everything else in the body stays exactly as it was):
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="data:,">
<title>Foggy Weather (after)</title>
<link rel="stylesheet" href="/theme.css">
<script src="/analytics.js?ms=600" async></script>
<link rel="stylesheet" href="/print.css?ms=900" media="print">
<script src="/app-fixed.js" defer></script>
</head>In app-fixed.js, the load handler does the same work in a way the main thread can absorb: the busy calculation is sliced into 30 ms chunks, and the card fitting batches all reads before all writes:
// app-fixed.js — the fixed page script: short tasks, batched layout.
function busy(ms) {
const start = performance.now();
while (performance.now() - start < ms) {
// stand-in for real work: sorting and reducing forecast data
}
}
function fitCards() {
const cards = [...document.querySelectorAll('.card')];
const widths = cards.map((card) => card.parentElement.offsetWidth);
cards.forEach((card, i) => {
card.style.width = widths[i] / 3 - 12 + 'px';
});
}
window.addEventListener('load', () => {
const CHUNKS = 8;
const CHUNK_MS = 30;
let done = 0;
(function next() {
busy(CHUNK_MS);
done += 1;
if (done < CHUNKS) setTimeout(next, 0); // each chunk its own task
})();
fitCards(); // one layout instead of 300
});07. Step 6: measure again and compare
node measure.js fixed.htmlpage /fixed.html
time to first byte 2 ms
first contentful paint 40 ms
load event 950 ms
long tasks (>50 ms) 0 — []
total blocking time* 0 ms
resources (download ms, render-blocking status)
8 ms blocking /theme.css
609 ms non-blocking /analytics.js?ms=600
9 ms non-blocking /app-fixed.js
906 ms non-blocking /print.css?ms=900
* estimate: long-task time above the 50 ms thresholdCompare the two reports. First contentful paint: 952 ms to 40 ms, because the paint now waits only for the stylesheet the screen really uses. Long tasks: one 332 ms task down to none, because roughly the same work (eight 30 ms chunks, 240 ms in all, instead of one 220 ms block) now runs as eight short tasks with one batched layout. Total blocking time: 282 ms to 0. And note what did not improve: the load event still lands near a second, because the analytics tag and print sheet still download — they are simply no longer in the first paint's way. That distinction is the whole point: load measures when everything arrived; first paint measures when the user could read the page.
08. Check your understanding
09. Apply it
Extend the lab in one of these directions, in increasing order of effort:
- Add
?ms=delays to a fourth resource and predict, before measuring, whether it will move the first paint. Check with measure.js. - Record fixed.html in the Performance panel and compare its task list with slow.html: how many Layout events remain, and where did
busygo? - Move the forecast calculation into a Web Worker instead of slicing it, and confirm the long-task report stays empty even with a single 250 ms piece of work.
- Point measure.js at a real website, note its first paint and long tasks under throttling, and write the one-sentence diagnosis that names the dominant step — the deliverable the skill's practice task asks for.
10. Review prompt
Without looking back: name the three problems planted in slow.html and the fix each one got. Say what the Network panel told you that measure.js also printed, and what only the Performance panel could show. Define the total-blocking-time estimate in one sentence, and explain why the load event barely moved while first contentful paint dropped by 900 ms.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.