Frontend development · Intermediate · 26 min
Test and speed up a page on a slow phone connection
By Padding · Updated 18 Nov 2026
Chrome DevTools · Lighthouse 13.6.0 · Playwright 1.65.1 · checked in Chromium 159 · Node.js 26
You will measure a heavy clinic home page on a throttled slow mobile connection, set a 500 kB page weight budget with a check that fails when the page grows, and cut its images, JavaScript and third-party widget until it passes, with before and after numbers to show for it.
On this page
A page that feels instant on office Wi-Fi can take fifteen seconds on a phone with a weak signal, and every byte it sends comes out of someone's data allowance. Single metrics such as Largest Contentful Paint tell you when the page looked ready. This tutorial is about the whole bill: how many bytes the page makes a visitor download, where they come from, and how to stop the number creeping back up after you cut it.
You will work on the home page of Larkfield Clinic, the fictional community clinic used across this library. Its first version has the problems real sites ship with: a full-size photo straight from a camera, a date library loaded to print one line of text, and a chat widget from another company that loads on every visit. You will measure the page on a throttled slow mobile connection, set a budget, cut the page down, and end with a budget file, a script that fails when the page goes over it, and before and after numbers.
Everything runs on your machine: a small Node.js server plays both the clinic's site and the chat company, Lighthouse gives you the standard report, and a Playwright script applies the same slow profile and checks the budget.
Step 1 · Set up the project
Make a folder for the demo and install four packages at pinned versions. sharp resizes and converts images, moment is the date library the first version of the page uses, and playwright and lighthouse do the measuring:
mkdir -p ~/page-weight-demo/site/vendor ~/page-weight-demo/widget
cd ~/page-weight-demo
npm init -y > /dev/null
npm install sharp@0.35.5 moment@2.31.0
npm install --save-dev playwright@1.65.1 lighthouse@13.6.0Playwright drives its own copy of Chromium, which you download once. On Linux, add --with-deps to also install the system libraries Chromium needs:
npx playwright install chromiumNow generate the heavy files. The script below writes a 1,600 by 1,000 pixel PNG in place of the clinic photo (a smooth pattern, so you need no image of your own), and a stand-in for a third-party chat widget: a script, a stylesheet and an avatar image. The widget script carries 2,000 canned replies, which is how it reaches the size of a real vendor bundle:
cat > make-assets.mjs <<'JS'
import { writeFile } from 'node:fs/promises'
import sharp from 'sharp'
// A smooth pattern that stands in for a photograph
function pattern(width, height) {
const pixels = new Uint8ClampedArray(width * height * 3)
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const i = (y * width + x) * 3
const wave = Math.sin(x / 23) * Math.cos(y / 17) * 40 + Math.sin((x + y) / 7) * 12
pixels[i] = 60 + (x / width) * 120 + wave
pixels[i + 1] = 110 + (y / height) * 80 + wave
pixels[i + 2] = 150 - (x / width) * 50 + wave
}
}
return sharp(Buffer.from(pixels.buffer), { raw: { width, height, channels: 3 } }).png()
}
// The clinic photo, uploaded at full size
await pattern(1600, 1000).toFile('site/hero.png')
// A stand-in for a third-party chat widget: a script, a stylesheet and an avatar
await pattern(160, 160).toFile('widget/avatar.png')
const replies = Array.from({ length: 2000 }, (_, i) =>
`Saved reply ${i}: thanks for your message, someone from the clinic will answer shortly.`)
await writeFile('widget/chat.js', `(() => {
const replies = ${JSON.stringify(replies)}
const origin = new URL(document.currentScript.src).origin
const start = () => {
const style = document.createElement('link')
style.rel = 'stylesheet'
style.href = origin + '/chat.css'
document.head.append(style)
const launcher = document.createElement('button')
launcher.type = 'button'
launcher.className = 'chat-launcher'
launcher.title = replies.length + ' saved replies'
launcher.innerHTML = '<img src="' + origin + '/avatar.png" alt="" width="40" height="40"> Chat with us'
document.body.append(launcher)
}
if (document.body) start()
else document.addEventListener('DOMContentLoaded', start)
})()
`)
await writeFile('widget/chat.css', `.chat-launcher { position: fixed; right: 1rem; bottom: 1rem; display: flex; align-items: center; gap: 0.5rem; padding: 0.5rem 1rem; border: 0; border-radius: 2rem; background: #0F5E5A; color: #FFFFFF; font: inherit; }
.chat-launcher img { border-radius: 50%; }
`)
JS
node make-assets.mjs
cp node_modules/moment/min/moment-with-locales.min.js site/vendor/
ls -l site site/vendor widgetThe last command copies Moment's browser build into the site, the way many projects vendor a library. This build includes every locale Moment supports.
Check it worked
The listing shows hero.png at about 2,490,000 bytes, moment-with-locales.min.js at about 391,000 bytes, and in widget, chat.js at about 180,000 bytes and avatar.png at about 63,000 bytes. Those four files are what the page is about to make every visitor download.
Step 2 · Build the page and look at it on a slow connection
The page is the clinic's Home screen: a photo, the five services, a line with today's date and a button to start booking. The date line is filled in by app.js using Moment. The chat widget is loaded from a second address, localhost:8091, which the browser treats as a different site, as it would a vendor's domain:
cat > site/style.css <<'CSS'
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; line-height: 1.5; color: #1B1F24; background: #F6F7F8; }
header { padding: 0.75rem 1rem; background: #0F5E5A; color: #FFFFFF; font-weight: 700; }
main { max-width: 40rem; margin: 0 auto; padding: 1rem; }
.hero { display: block; width: 100%; height: auto; border-radius: 0.5rem; }
.services { padding: 0; list-style: none; }
.services li { padding: 0.75rem 1rem; border-bottom: 1px solid #D5D9DF; background: #FFFFFF; }
.button { display: inline-block; padding: 0.75rem 1.25rem; border-radius: 0.5rem; background: #0F5E5A; color: #FFFFFF; font-weight: 600; text-decoration: none; }
#chat { margin-top: 1rem; padding: 0.5rem 1rem; border: 1px solid #7D8592; border-radius: 0.5rem; background: #FFFFFF; font: inherit; }
CSS
cat > site/app.js <<'JS'
document.querySelector('#today').textContent = `Today: ${moment().format('dddd D MMMM')}`
JS
cat > site/index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Larkfield Clinic</title>
<link rel="stylesheet" href="style.css">
<script src="vendor/moment-with-locales.min.js" defer></script>
<script src="app.js" defer></script>
<script src="http://localhost:8091/chat.js" async></script>
</head>
<body>
<header>Larkfield Clinic</header>
<main>
<img class="hero" src="hero.png" alt="The front entrance of Larkfield Clinic">
<h1>Book an appointment</h1>
<p id="today">Today</p>
<ul class="services">
<li>GP appointment · 10 min</li>
<li>Nurse appointment · 15 min</li>
<li>Blood test · 10 min</li>
<li>Vaccination · 15 min</li>
<li>Medication review · 20 min</li>
</ul>
<a class="button" href="#choose-a-service">Book an appointment</a>
</main>
</body>
</html>
HTMLThe server sends files from site on port 8090 and from widget on port 8091. It does no compression and no caching, so what you measure is the files themselves. It only listens on your own machine and refuses paths outside the two folders:
cat > serve.mjs <<'JS'
import { createServer } from 'node:http'
import { readFile } from 'node:fs/promises'
import path from 'node:path'
const types = {
'.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript',
'.png': 'image/png', '.webp': 'image/webp',
}
function serve(folder, port) {
const root = path.resolve(folder)
createServer(async (req, res) => {
let name = new URL(req.url, 'http://localhost').pathname
if (name.endsWith('/')) name += 'index.html'
const file = path.join(root, name)
if (!file.startsWith(root + path.sep)) return res.writeHead(403).end()
try {
const body = await readFile(file)
res.writeHead(200, {
'content-type': types[path.extname(file)] ?? 'application/octet-stream',
'cache-control': 'no-store',
})
res.end(body)
} catch {
res.writeHead(404).end()
}
}).listen(port, '127.0.0.1', () => console.log(`${folder} on http://127.0.0.1:${port}/`))
}
serve('site', 8090)
serve('widget', 8091)
JSStart it in a second terminal, from the same folder, and leave it running:
cd ~/page-weight-demo
node serve.mjsNow look at it the way a visitor on a weak signal would. Open http://127.0.0.1:8090/ in Chrome and open DevTools (F12). Turn on the device toolbar (the phone and tablet icon) so the page has a phone-sized viewport. In the Network panel, tick Disable cache, open the throttling menu, which says No throttling, and choose Slow 4G (older versions call the same preset Fast 3G). Reload and watch.
Check it worked
The terminal running the server prints site on http://127.0.0.1:8090/ and widget on http://127.0.0.1:8091/. From your first terminal, fetch the two biggest files:
curl -s -o /dev/null -w '%{http_code} %{size_download} bytes\n' http://127.0.0.1:8090/hero.png
curl -s -o /dev/null -w '%{http_code} %{size_download} bytes\n' http://localhost:8091/chat.jsBoth lines start with 200, with about 2,494,000 and 180,000 bytes. In the throttled browser, the text appears early, then the photo fills in from the top for many seconds, and a round Chat with us button appears in the bottom corner. The bar at the bottom of the Network panel reads something like 8 requests and 3.1 MB transferred. Set throttling back to No throttling when you are done, because the setting stays on while DevTools is open.
Step 3 · Measure it with Lighthouse on a slow mobile profile
Lighthouse is Chrome's auditing tool. Its default run pretends to be a mid-range phone: a 412 by 823 pixel screen, a connection with a 150 ms round trip and about 1.6 Mbps download and 750 Kbps upload, and a processor four times slower than your machine's. By default it does not slow the real load down. It loads the page at full speed and then simulates how long the same requests would take on that profile, which keeps results steady between runs. You can run it from the Lighthouse panel in DevTools, or from the terminal as here, which saves the report as a file you can keep.
Lighthouse drives a Chrome it finds on your machine. To use the Chromium that Playwright downloaded, so both tools measure with the same browser, point CHROME_PATH at it:
cd ~/page-weight-demo
export CHROME_PATH="$(node -e "import('playwright').then((p) => console.log(p.chromium.executablePath()))")"
echo "$CHROME_PATH"Run a performance-only audit and save it as both JSON and HTML:
npx lighthouse http://127.0.0.1:8090/ --only-categories=performance --output=json --output=html --output-path=./lh-before --chrome-flags="--headless" --quietThe run takes up to a minute and writes lh-before.report.json and lh-before.report.html. Open the HTML file in a browser for the full report. For the numbers this tutorial cares about, a short script reads the JSON. total-byte-weight is the sum of everything transferred, and resource-summary splits it by type and counts third-party requests:
cat > lh-summary.mjs <<'JS'
import { readFile } from 'node:fs/promises'
const report = JSON.parse(await readFile(process.argv[2], 'utf8'))
const kib = (bytes) => `${Math.round(bytes / 1024)} KiB`
console.log('Performance score:', Math.round(report.categories.performance.score * 100))
console.log('Total byte weight:', kib(report.audits['total-byte-weight'].numericValue))
console.log('LCP (simulated):', Math.round(report.audits['largest-contentful-paint'].numericValue), 'ms')
for (const row of report.audits['resource-summary'].details.items) {
console.log(` ${row.label}: ${row.requestCount} requests, ${kib(row.transferSize)}`)
}
JS
node lh-summary.mjs lh-before.report.jsonCheck it worked
The summary prints a low performance score, a total byte weight of roughly 3,000 KiB, and a simulated Largest Contentful Paint of many seconds. In the rows, Image is by far the largest, Script is next, and Third-party shows three requests. Lighthouse counts in KiB (1,024 bytes), while DevTools and the rest of this tutorial use kB (1,000 bytes), so its totals look about 2% smaller. In the HTML report, the diagnostics include "Avoid enormous network payloads", which lists the same files biggest first.
Step 4 · Set a page weight budget and a check that enforces it
A budget turns "the page feels heavy" into a number a build can fail on. Pick limits from what your visitors can afford, not from what the page weighs today. 500 kB for a whole page is a reasonable target for a content page like this one. On the throttled profile it is about two and a half seconds of pure download, and a visitor on a prepaid bundle could open six such pages for the data this one costs now. That matters for most of the world. Across much of Africa, South Asia and Latin America, people buy data in small prepaid amounts and browse on low-cost Android phones, so a heavy page costs them money as well as time.
Write the budget as a file the check reads. Bytes are the main limits, because they are the same on every run. The load time limit is a backstop with plenty of margin, because timings vary a little from run to run:
cat > budget.json <<'JSON'
{
"totalKB": 500,
"scriptKB": 100,
"imageKB": 250,
"thirdPartyRequests": 0,
"loadMs": 5000
}
JSONthirdPartyRequests is set to zero on purpose. Every script from another company is weight you do not control, and it can grow without a single change to your code. A zero limit means adding one is a decision someone makes in review, not an accident.
The check opens the page in Chromium with a phone viewport, then uses the Chrome DevTools Protocol, the same channel DevTools uses, to apply the same connection Lighthouse's mobile profile models, plus a fourfold CPU slowdown, to the real load. Lighthouse itself simulates that connection rather than applying it, so expect your timings to be close to its numbers, not identical. It records the bytes transferred for every response, headers included, and compares the totals with the budget:
cat > check-budget.mjs <<'JS'
import { chromium } from 'playwright'
import { readFile, writeFile } from 'node:fs/promises'
const args = process.argv.slice(2)
const saveAt = args.indexOf('--save')
const savePath = saveAt === -1 ? null : args.splice(saveAt, 2)[1]
const url = args[0] ?? 'http://127.0.0.1:8090/'
const budget = JSON.parse(await readFile(new URL('./budget.json', import.meta.url), 'utf8'))
// The connection Lighthouse's mobile profile models: 150 ms round trip, 1.6 Mbps down, 750 Kbps up (in bytes per second)
const slowMobile = { urlPattern: '', latency: 150, downloadThroughput: (1.6 * 1024 * 1024) / 8, uploadThroughput: (750 * 1024) / 8 }
const browser = await chromium.launch()
const context = await browser.newContext({ viewport: { width: 412, height: 823 }, deviceScaleFactor: 1.75, isMobile: true, hasTouch: true })
const page = await context.newPage()
const cdp = await context.newCDPSession(page)
const responses = new Map()
cdp.on('Network.responseReceived', ({ requestId, type, response }) => {
responses.set(requestId, { url: response.url, type: type.toLowerCase(), bytes: 0 })
})
cdp.on('Network.loadingFinished', ({ requestId, encodedDataLength }) => {
const entry = responses.get(requestId)
if (entry) entry.bytes = encodedDataLength
})
await cdp.send('Network.enable')
await cdp.send('Network.setCacheDisabled', { cacheDisabled: true })
await cdp.send('Network.emulateNetworkConditionsByRule', { matchedNetworkConditions: [slowMobile] })
await cdp.send('Emulation.setCPUThrottlingRate', { rate: 4 })
await page.goto(url, { waitUntil: 'load', timeout: 120_000 })
await page.waitForTimeout(2000) // let anything started at load finish
const loadMs = await page.evaluate(() => Math.round(performance.getEntriesByType('navigation')[0].loadEventEnd))
await browser.close()
const kB = (bytes) => Math.round(bytes / 1000)
const pageHost = new URL(url).hostname
const byType = {}
let total = 0
let thirdPartyRequests = 0
for (const { url: address, type, bytes } of responses.values()) {
byType[type] ??= { requests: 0, bytes: 0 }
byType[type].requests++
byType[type].bytes += bytes
total += bytes
if (new URL(address).hostname !== pageHost) thirdPartyRequests++
}
const result = {
url, loadMs, requests: responses.size, totalKB: kB(total),
scriptKB: kB(byType.script?.bytes ?? 0), imageKB: kB(byType.image?.bytes ?? 0), thirdPartyRequests,
}
console.log(`${url} on a throttled slow mobile profile`)
for (const [type, row] of Object.entries(byType).sort((a, b) => b[1].bytes - a[1].bytes)) {
console.log(` ${type.padEnd(12)} ${String(row.requests).padStart(3)} requests ${String(kB(row.bytes)).padStart(7)} kB`)
}
const checks = [
['Total weight (kB)', result.totalKB, budget.totalKB],
['JavaScript (kB)', result.scriptKB, budget.scriptKB],
['Images (kB)', result.imageKB, budget.imageKB],
['Third-party requests', result.thirdPartyRequests, budget.thirdPartyRequests],
['Load time (ms)', result.loadMs, budget.loadMs],
]
let failed = 0
for (const [label, actual, limit] of checks) {
if (actual > limit) failed++
console.log(`${actual > limit ? 'FAIL' : 'PASS'} ${label}: ${actual} (budget ${limit})`)
}
if (savePath) await writeFile(savePath, JSON.stringify(result, null, 2) + '\n')
if (failed) {
console.log(`${failed} over budget`)
process.exitCode = 1
} else {
console.log('Within budget')
}
JS
npm pkg set scripts.budget="node check-budget.mjs"A third-party request here means any request to a host name other than the page's own, subdomains included, so static.example.com counts as third party for www.example.com. If your site serves its own files from a CDN or a static subdomain, add those host names to the comparison on the thirdPartyRequests++ line so they are not counted. Lighthouse's own count is looser and treats subdomains of your domain as first party, so the two numbers can differ. The script exits with code 1 when anything is over, which is what makes a CI job fail. Run it on the page as it is and save the numbers as your "before":
npm run budget -- --save before.json || echo "Over budget, exit code $?"Check it worked
The load takes a while, because it is really throttled. The breakdown lists image first at about 2,560 kB, then script at about 570 kB, and then the stylesheets and the document. All five lines say FAIL: total weight at about 3,130 kB, JavaScript, images, three third-party requests, and a load time of well over ten seconds. The last line is Over budget, exit code 1, and before.json holds the same numbers.
Step 5 · Shrink the hero image
The photo is 1,600 pixels wide and saved as PNG, which keeps every pixel exactly and suits screenshots and diagrams, not photographs. On a phone the image is shown about 400 CSS pixels wide, and even a high-density screen needs only about twice that. Resize it to 800 pixels wide and save it as WebP, which every current browser supports and which compresses photographs far better:
cat > shrink-hero.mjs <<'JS'
import sharp from 'sharp'
const info = await sharp('site/hero.png')
.resize({ width: 800 })
.webp({ quality: 70 })
.toFile('site/hero-800.webp')
console.log(`hero-800.webp: ${info.width} x ${info.height}, ${Math.round(info.size / 1000)} kB`)
JS
node shrink-hero.mjsPoint the page at the new file. The width and height attributes tell the browser the image's shape before it arrives, so the text below does not jump when it loads:
cat > site/index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Larkfield Clinic</title>
<link rel="stylesheet" href="style.css">
<script src="vendor/moment-with-locales.min.js" defer></script>
<script src="app.js" defer></script>
<script src="http://localhost:8091/chat.js" async></script>
</head>
<body>
<header>Larkfield Clinic</header>
<main>
<img class="hero" src="hero-800.webp" width="800" height="500" alt="The front entrance of Larkfield Clinic">
<h1>Book an appointment</h1>
<p id="today">Today</p>
<ul class="services">
<li>GP appointment · 10 min</li>
<li>Nurse appointment · 15 min</li>
<li>Blood test · 10 min</li>
<li>Vaccination · 15 min</li>
<li>Medication review · 20 min</li>
</ul>
<a class="button" href="#choose-a-service">Book an appointment</a>
</main>
</body>
</html>
HTML
npm run budget || echo "Over budget, exit code $?"A real photograph will not shrink as far as this smooth pattern, but resizing to the displayed size and switching format usually removes most of the weight. To serve different sizes to different screens, see Serve responsive images with srcset and picture.
Check it worked
shrink-hero.mjs prints hero-800.webp: 800 x 500 and a size of about 21 kB. In the budget output, images drop from about 2,560 kB to under 100 kB, because the avatar from the chat widget is still there. The total falls to about 660 kB, still over 500, and JavaScript and third-party requests still fail.
Step 6 · Replace the date library with the browser's own
The page loads 391 kB of Moment, with every locale it supports, to print one line such as Today: Wednesday 18 November. Browsers have had date formatting built in for years through Intl.DateTimeFormat, and the Moment project itself describes Moment as a legacy project in maintenance mode and suggests alternatives for new work. Rewrite app.js without it:
cat > site/app.js <<'JS'
const today = new Intl.DateTimeFormat('en-GB', { weekday: 'long', day: 'numeric', month: 'long' }).format(new Date())
document.querySelector('#today').textContent = `Today: ${today}`
JSThe en-GB locale gives the same day, date and month order Moment printed. The locale data ships with the browser, so a French-speaking clinic could pass fr-FR and get mercredi 18 novembre with no extra download, and the same goes for the many other languages the browser knows.
Remove the Moment script tag from the page:
cat > site/index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Larkfield Clinic</title>
<link rel="stylesheet" href="style.css">
<script src="app.js" defer></script>
<script src="http://localhost:8091/chat.js" async></script>
</head>
<body>
<header>Larkfield Clinic</header>
<main>
<img class="hero" src="hero-800.webp" width="800" height="500" alt="The front entrance of Larkfield Clinic">
<h1>Book an appointment</h1>
<p id="today">Today</p>
<ul class="services">
<li>GP appointment · 10 min</li>
<li>Nurse appointment · 15 min</li>
<li>Blood test · 10 min</li>
<li>Vaccination · 15 min</li>
<li>Medication review · 20 min</li>
</ul>
<a class="button" href="#choose-a-service">Book an appointment</a>
</main>
</body>
</html>
HTML
npm run budget || echo "Over budget, exit code $?"Before you remove a library in a real project, search the code for every use of it. Here app.js was the only one. A bundler's analysis report, or the Coverage panel in DevTools, shows which large modules ship and how much of each actually runs.
Check it worked
Reload http://127.0.0.1:8090/ in your browser. The date line reads the same as before, for example Today: Wednesday 18 November. In the budget output, JavaScript falls from about 570 kB to about 180 kB, and nearly all of what is left is chat.js from the widget. The total is under 300 kB, so the total weight now passes, but JavaScript and third-party requests still fail.
Step 7 · Load the chat widget only when someone asks for it
The chat widget is the hardest kind of weight to manage: you do not write it, it can change without notice, and most visitors never open it. Removing it may not be your call, but you can stop it loading for everyone. Put a plain button in its place, a facade, and fetch the real widget only when someone presses it:
cat >> site/app.js <<'JS'
document.querySelector('#chat').addEventListener('click', (event) => {
const script = document.createElement('script')
script.src = 'http://localhost:8091/chat.js'
document.body.append(script)
event.currentTarget.remove()
}, { once: true })
JS
cat > site/index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Larkfield Clinic</title>
<link rel="stylesheet" href="style.css">
<script src="app.js" defer></script>
</head>
<body>
<header>Larkfield Clinic</header>
<main>
<img class="hero" src="hero-800.webp" width="800" height="500" alt="The front entrance of Larkfield Clinic">
<h1>Book an appointment</h1>
<p id="today">Today</p>
<ul class="services">
<li>GP appointment · 10 min</li>
<li>Nurse appointment · 15 min</li>
<li>Blood test · 10 min</li>
<li>Vaccination · 15 min</li>
<li>Medication review · 20 min</li>
</ul>
<a class="button" href="#choose-a-service">Book an appointment</a>
<p><button type="button" id="chat">Chat with us</button></p>
</main>
</body>
</html>
HTML
npm run budget -- --save after.jsonThe facade is a real <button>, so it works with a keyboard and a screen reader. When pressed, it adds the vendor's script and removes itself, and the vendor's own launcher takes its place. The visitor waits a moment once, on the visit where they want to chat, and every other visit is spared the download. Many vendors document a way to load their widget on demand, so check their documentation before you write your own.
Check it worked
The budget check ends with Within budget and exits without an error, and after.json is saved. The breakdown shows about four requests and a total of about 25 kB, with no third-party requests and a load time of around a second. In your browser, reload the page with the Network panel open: nothing comes from localhost:8091. Press Chat with us: chat.js, chat.css and avatar.png load, and the round launcher appears in the corner.
Step 8 · Compare the numbers and catch the page growing again
Put the two runs side by side:
cat > compare.mjs <<'JS'
import { readFile } from 'node:fs/promises'
const read = async (file) => JSON.parse(await readFile(file, 'utf8'))
const [before, after] = await Promise.all([read('before.json'), read('after.json')])
const rows = [
['Total weight (kB)', 'totalKB'], ['JavaScript (kB)', 'scriptKB'], ['Images (kB)', 'imageKB'],
['Requests', 'requests'], ['Third-party requests', 'thirdPartyRequests'], ['Load, slow mobile (ms)', 'loadMs'],
]
console.log(''.padEnd(24), 'before'.padStart(8), 'after'.padStart(8))
for (const [label, key] of rows) console.log(label.padEnd(24), String(before[key]).padStart(8), String(after[key]).padStart(8))
JS
node compare.mjsThen run Lighthouse again, so you have the standard report to show alongside your own numbers:
npx lighthouse http://127.0.0.1:8090/ --only-categories=performance --output=json --output=html --output-path=./lh-after --chrome-flags="--headless" --quietnode lh-summary.mjs lh-after.report.jsonA budget only helps if something enforces it. Suppose a colleague adds a promotions page and drops the original PNG in as a banner. Create that page and point the check at it:
cat > site/promo.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Flu vaccinations · Larkfield Clinic</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>Larkfield Clinic</header>
<main>
<img class="hero" src="hero.png" alt="The front entrance of Larkfield Clinic">
<h1>Flu vaccinations are open</h1>
<a class="button" href="#choose-a-service">Book a vaccination</a>
</main>
</body>
</html>
HTML
npm run budget -- http://127.0.0.1:8090/promo.html || echo "Budget check failed, exit code $?"In your project, run npm run budget in your CI pipeline after the build, with the site served locally as here, once for each important page. Because the script exits with code 1 when anything is over, the job fails and the change cannot merge until someone shrinks the page or agrees, in review, to raise the budget. If your pipeline already runs Node tests, Run Node tests in GitHub Actions shows the job setup. Install Chromium there with npx playwright install --with-deps chromium.
Check it worked
The comparison prints something like this, with your load times a little different:
before after
Total weight (kB) 3130 25
JavaScript (kB) 572 1
Images (kB) 2558 21
Requests 8 4
Third-party requests 3 0
Load, slow mobile (ms) 15500 900The second Lighthouse summary shows a total byte weight of about 25 KiB, a much higher performance score, and the Third-party row, if listed, shows 0 requests. The promotions page fails the budget on total weight and images and the last line is Budget check failed, exit code 1. Remove that page once you have seen it fail:
rm site/promo.htmlStep 9 · Clean up
Stop the server with Ctrl+C in its terminal. Then delete the demo folder:
Playwright keeps its Chromium download, a few hundred megabytes, in a shared cache folder outside the project, so deleting the folder alone leaves it behind. Remove it first, from inside the demo folder, then delete the folder:
cd ~/page-weight-demo
npx playwright uninstall
cd ~
rm -rf ~/page-weight-demonpx playwright uninstall removes the browsers that only this project was using. If another project on your machine needs the same Chromium, Playwright keeps it, so that project has nothing to download again. npx playwright uninstall --all removes every browser Playwright has downloaded, for every project.
Check it worked
npx playwright uninstall finishes without an error, ls ~/page-weight-demo reports that there is no such file or directory, and http://127.0.0.1:8090/ no longer loads in your browser.
Next steps
- Weight is only part of the experience on a weak connection. Design for slow networks and costly data covers what the page should show and do while it loads, and when it fails.
- For the moment the page looks ready, rather than how much it costs, improve Largest Contentful Paint.
- To send each screen the image size it needs, serve responsive images with srcset and picture.
Part of these paths
Related tutorials
- Design for slow networks and costly dataYou will have a per-screen data budget for the Larkfield Clinic booking flow, Figma frames for what each screen shows offline, a save-and-resume state, a use-less-data option and SMS confirmation text that fits in one message.
- How to Improve Largest Contentful Paint (LCP) on Your WebsiteYou will measure Largest Contentful Paint on a deliberately slow page, find which of its four parts is wasting time, fix it by making the hero image discoverable early and by serving a smaller one, and learn how to check the result with field data, because 2.5 seconds is the line between good and not good.
- Serve responsive images with srcset and pictureYou will have a clinic web page whose photos come in several widths and in AVIF, WebP and JPEG, with a closer crop of the entrance on phones, lazy loading below the fold and space held for every image, plus a script that reports which file each screen size downloads.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials