Frontend development · Intermediate · 24 min
Measure Core Web Vitals with Lighthouse and the web-vitals library
By Padding · Updated 18 Nov 2026
Node.js 26 · Lighthouse 13.6.0 · web-vitals 6.2.3 · Playwright 1.65.1 · checked in Chromium 159
You will measure a page's Core Web Vitals twice, once in the lab with the Lighthouse CLI and once from real visits with the web-vitals library sending LCP, INP and CLS to your own collector, and end with a budget check that fails when LCP goes over 2.5 seconds.
On this page
Core Web Vitals are the three numbers Google uses to describe how a page feels to the people using it. Largest Contentful Paint (LCP) is when the biggest thing in the first screen finished drawing, and it is good at 2.5 seconds or less. Interaction to Next Paint (INP) is how long the page takes to respond visibly to taps, clicks and key presses, good at 200 ms or less. Cumulative Layout Shift (CLS) scores how much content jumps around while you read it, good at 0.1 or less. A page passes when at least three in four of its real visits meet each target.
There are two ways to get those numbers, and you need both. Lab data comes from a tool such as Lighthouse loading the page once under fixed conditions: repeatable, available before launch, but only ever one imaginary visitor. Field data comes from real visits, on real phones and networks: the numbers that count, but only once people use the page. In this tutorial you get each kind for the same small page, then turn the lab result into a check that a build can fail on.
The page is the opening hours page of Larkfield Clinic, the fictional community clinic used across this library. It has three faults on purpose: a hero image far bigger than it needs to be, a notice that appears late and pushes the page down, and a button whose click handler blocks the page for 300 ms. Each one shows up in a different metric.
Step 1 · Set up the demo page and its server
Make a folder for the demo and install the three packages at pinned versions. lighthouse and playwright are tools you run, so they go in as development dependencies. web-vitals ends up in the page itself:
mkdir -p ~/web-vitals-demo/site
cd ~/web-vitals-demo
npm init -y > /dev/null
npm install --save-dev lighthouse@13.6.0 playwright@1.65.1
npm install web-vitals@6.2.3Playwright drives its own copy of Chromium, which you download once. Lighthouse will use the same browser, so both tools measure with one Chromium. On Linux, add --with-deps to also install the system libraries Chromium needs:
npx playwright install chromiumNext, two images. The script writes them as PNG files with Node.js alone, so you need no photo of your own. hero-large.png is 1,200 by 800 pixels of random noise, which barely compresses and so behaves like a photo straight from a camera. hero-small.png is a smooth 600 by 400 pixel gradient, the size the page actually shows it:
cd ~/web-vitals-demo
cat > make-images.mjs <<'JS'
import { writeFileSync } from 'node:fs'
import { randomFillSync } from 'node:crypto'
import { deflateSync, crc32 } from 'node:zlib'
function chunk(type, data) {
const length = Buffer.alloc(4)
length.writeUInt32BE(data.length)
const body = Buffer.concat([Buffer.from(type, 'ascii'), data])
const crc = Buffer.alloc(4)
crc.writeUInt32BE(crc32(body))
return Buffer.concat([length, body, crc])
}
function png(width, height, fillRow) {
const header = Buffer.alloc(13)
header.writeUInt32BE(width, 0)
header.writeUInt32BE(height, 4)
header[8] = 8 // 8 bits per channel
header[9] = 2 // RGB
const rowBytes = 1 + width * 3 // each row starts with a filter byte of 0
const raw = Buffer.alloc(height * rowBytes)
for (let y = 0; y < height; y++) {
fillRow(raw.subarray(y * rowBytes + 1, (y + 1) * rowBytes), y)
}
const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])
return Buffer.concat([signature, chunk('IHDR', header), chunk('IDAT', deflateSync(raw)), chunk('IEND', Buffer.alloc(0))])
}
writeFileSync('site/hero-large.png', png(1200, 800, (row) => randomFillSync(row)))
writeFileSync('site/hero-small.png', png(600, 400, (row, y) => {
for (let x = 0; x < 600; x++) {
row[x * 3] = 15 + ((x / 8) | 0)
row[x * 3 + 1] = 94 + ((y / 8) | 0)
row[x * 3 + 2] = 90
}
}))
JS
node make-images.mjs
ls -l siteNow the page. It shows the large image with no width or height, adds the notice 600 ms after the page starts, and runs a 300 ms busy loop when someone clicks the button:
cd ~/web-vitals-demo
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>Opening hours · Larkfield Clinic</title>
<style>
body { margin: 0; font-family: system-ui, sans-serif; color: #1b1f24; background: #f6f7f8; }
main { max-width: 40rem; margin: 0 auto; padding: 1rem; }
.hero { display: block; width: 100%; height: auto; }
.notice { box-sizing: border-box; height: 140px; margin: 0; padding: 1rem; background: #0f5e5a; color: #ffffff; }
button { min-height: 48px; padding: 0 1rem; font: inherit; }
</style>
</head>
<body>
<div id="notice-slot"></div>
<main>
<h1>Opening hours</h1>
<img class="hero" src="hero-large.png" alt="">
<p>Larkfield Clinic is open six days a week. Walk-in appointments are available every morning.</p>
<button id="show-hours" type="button">Show this week's hours</button>
<p id="hours" hidden>Monday to Friday 08:00 to 18:00. Saturday 09:00 to 13:00.</p>
</main>
<script>
// A notice that arrives after the page has drawn, pushing everything down
setTimeout(() => {
const notice = document.createElement('p')
notice.className = 'notice'
notice.textContent = 'Flu vaccinations are available every Saturday this month.'
document.getElementById('notice-slot').append(notice)
}, 600)
// A click handler that keeps the main thread busy for 300 ms
document.getElementById('show-hours').addEventListener('click', () => {
const end = performance.now() + 300
while (performance.now() < end) {}
document.getElementById('hours').hidden = false
})
</script>
</body>
</html>
HTMLThe server sends files from site and, at POST /vitals, accepts the measurements the page will send in a later step and appends them to vitals.jsonl, one JSON object per line. It keeps only the fields it expects, refuses bodies over 10 kB and paths outside site, and listens only on your own machine:
cd ~/web-vitals-demo
cat > server.mjs <<'JS'
import { createServer } from 'node:http'
import { readFile, appendFile } from 'node:fs/promises'
import path from 'node:path'
const root = path.resolve('site')
const types = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.png': 'image/png' }
const metricNames = new Set(['LCP', 'INP', 'CLS'])
async function collect(req, res) {
let body = ''
for await (const part of req) {
body += part
if (body.length > 10_000) return res.writeHead(413).end()
}
try {
const metrics = JSON.parse(body)
if (!Array.isArray(metrics)) throw new Error('expected an array')
const lines = metrics
.filter((m) => metricNames.has(m.name) && Number.isFinite(m.value))
.map(({ name, value, rating, id, navigationType, page }) =>
JSON.stringify({ name, value, rating, id, navigationType, page, receivedAt: new Date().toISOString() }) + '\n')
.join('')
await appendFile('vitals.jsonl', lines)
res.writeHead(204).end()
} catch {
res.writeHead(400).end()
}
}
createServer(async (req, res) => {
const url = new URL(req.url, 'http://127.0.0.1')
if (req.method === 'POST' && url.pathname === '/vitals') return collect(req, res)
const file = path.join(root, url.pathname === '/' ? 'index.html' : url.pathname)
if (!file.startsWith(root + path.sep)) return res.writeHead(403).end()
try {
const data = await readFile(file)
res.writeHead(200, { 'Content-Type': types[path.extname(file)] ?? 'application/octet-stream', 'Cache-Control': 'no-store' })
res.end(data)
} catch {
res.writeHead(404).end('Not found')
}
}).listen(8095, '127.0.0.1', () => console.log('Serving on http://127.0.0.1:8095/'))
JSStart it in a second terminal, from the demo folder, and leave it running:
cd ~/web-vitals-demo
node server.mjsCheck it worked
ls -l site lists hero-large.png at a little under 3 MB and hero-small.png at a few kilobytes, plus index.html. The second terminal prints Serving on http://127.0.0.1:8095/. Open that address in Chrome: the heading and image appear, and a moment later the green notice pushes them down. Click Show this week's hours and the page hangs briefly before the hours appear.
curl -s -o /dev/null -w '%{http_code} %{size_download} bytes\n' http://127.0.0.1:8095/hero-large.pngThat prints 200 and the size of the large image.
Step 2 · Run Lighthouse from the terminal
Lighthouse is Chrome's page auditing tool. You can run it from the Lighthouse panel in DevTools, but the terminal version saves the result as a file, which is what a check in a build needs. By default it imitates a mid-range phone: a 412 by 823 pixel screen, a slow 4G connection with a 150 ms round trip, and a processor four times slower than yours. It does not slow the real load down. It loads the page at full speed, then simulates how long the same work would take on that phone, which keeps runs consistent.
Lighthouse launches the Chrome it finds on your machine, or the one in CHROME_PATH. Point it at the Chromium Playwright downloaded:
cd ~/web-vitals-demo
export CHROME_PATH="$(node -e "import('playwright').then((p) => console.log(p.chromium.executablePath()))")"
echo "$CHROME_PATH"Run only the performance category and save the result as both JSON and HTML:
npx lighthouse http://127.0.0.1:8095/ --only-categories=performance --output=json --output=html --output-path=./lh-before --chrome-flags="--headless" --quiet--quiet hides the progress log, and --chrome-flags="--headless" runs Chromium without a window. Leave out --headless once to watch it work.
Check it worked
After up to a minute, the folder holds lh-before.report.json and lh-before.report.html:
cd ~/web-vitals-demo
ls -l lh-before.report.*Open lh-before.report.html in a browser. The performance score at the top is low, and the metrics section is mostly red.
Step 3 · Read the metrics from the JSON report
The HTML report is for people. The JSON is for scripts, and everything in the HTML is in it. Each metric is an entry in audits, with numericValue (milliseconds, or a plain score for CLS), displayValue (the text the report shows) and score (0 to 1). This script prints the version, the device it pretended to be, the overall score and the five lab metrics:
cd ~/web-vitals-demo
cat > read-report.mjs <<'JS'
import { readFile } from 'node:fs/promises'
const report = JSON.parse(await readFile(process.argv[2], 'utf8'))
if (report.runtimeError) throw new Error(`Lighthouse could not finish: ${report.runtimeError.message}`)
console.log(`Lighthouse ${report.lighthouseVersion}, ${report.configSettings.formFactor}`)
console.log(`Performance score: ${Math.round(report.categories.performance.score * 100)}`)
for (const id of ['first-contentful-paint', 'largest-contentful-paint', 'total-blocking-time', 'cumulative-layout-shift', 'speed-index']) {
const audit = report.audits[id]
console.log(` ${audit.title}: ${audit.displayValue}`)
}
JS
node read-report.mjs lh-before.report.jsonTwo things are missing, and both matter. There is no INP, because INP needs someone to interact, and a page load has no interactions. Lighthouse only measures INP in timespan mode, where you record yourself or a script using the page. In a load report, Total Blocking Time (TBT) stands in for it: the time the main thread was too busy to respond. Second, none of this is field data. It is one simulated load, on one imaginary phone, of a page served from your own machine.
That is what lab data is for: comparing before and after, catching regressions, and testing pages nobody visits yet. It cannot tell you what your visitors experience. A clinic patient on a low-cost Android phone, on a prepaid bundle and a crowded cell, can be well behind Lighthouse's mid-range phone. Field data from real visits is what tells you that, and it is what the next two steps collect.
Check it worked
The output starts with Lighthouse 13.6.0, mobile and shows a low score. Largest Contentful Paint is many seconds, because the simulated slow connection has to download the 3 MB image before it can draw it. Cumulative Layout Shift is above 0. Total Blocking Time is low, because nothing blocks the page until someone clicks the button, which Lighthouse never does.
Step 4 · Report real visits with the web-vitals library
Browsers expose the raw measurements through PerformanceObserver, but turning them into the three metrics has many rules: which paint counts as largest, when LCP stops updating, how layout shifts are grouped, which interaction counts for INP. The web-vitals library, maintained by the Chrome team, implements those rules and calls you back with a finished value. Each callback receives a metric object with name, value, rating (good, needs-improvement or poor), and an id that stays the same for one page view.
Copy the library's ES module build into the site, so the page loads it from your own server. The file is about 9 kB, or a little over 3 kB gzipped:
cd ~/web-vitals-demo
cp node_modules/web-vitals/dist/web-vitals.js site/web-vitals.jsNow write site/vitals.js. It keeps every metric in a queue and sends the whole queue in one request when the page is hidden: when the visitor switches tab or app, locks the phone, or leaves. That is often the last moment a page can run code, and navigator.sendBeacon is built for it. The browser takes the request and delivers it even after the page has gone. If the browser refuses the beacon, for example because it is too big, fetch with keepalive tries instead:
cd ~/web-vitals-demo
cat > site/vitals.js <<'JS'
import { onCLS, onINP, onLCP } from './web-vitals.js'
const queue = []
function remember(metric) {
queue.push({
name: metric.name,
value: metric.value,
rating: metric.rating,
id: metric.id,
navigationType: metric.navigationType,
page: location.pathname,
})
}
function send() {
if (queue.length === 0) return
const body = JSON.stringify(queue.splice(0))
if (!navigator.sendBeacon('/vitals', body)) {
fetch('/vitals', { method: 'POST', body, keepalive: true })
}
}
onLCP(remember)
onINP(remember)
onCLS(remember)
addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') send()
})
addEventListener('pagehide', send)
JSA few details are worth knowing. LCP is final at the first click or key press, so it usually reaches the queue early. INP and CLS keep changing for as long as the page is open, so the library reports them when the page is hidden, and can report them again with the same id if the visitor comes back and keeps going. The collector keeps every report, and the summary in the next step uses the last one for each id. Batching all three into one beacon is also kinder to visitors paying for data by the megabyte: one small request per visit instead of three.
Load the script on the page. Rewrite index.html with one new line, the <script type="module"> before </body>:
cd ~/web-vitals-demo
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>Opening hours · Larkfield Clinic</title>
<style>
body { margin: 0; font-family: system-ui, sans-serif; color: #1b1f24; background: #f6f7f8; }
main { max-width: 40rem; margin: 0 auto; padding: 1rem; }
.hero { display: block; width: 100%; height: auto; }
.notice { box-sizing: border-box; height: 140px; margin: 0; padding: 1rem; background: #0f5e5a; color: #ffffff; }
button { min-height: 48px; padding: 0 1rem; font: inherit; }
</style>
</head>
<body>
<div id="notice-slot"></div>
<main>
<h1>Opening hours</h1>
<img class="hero" src="hero-large.png" alt="">
<p>Larkfield Clinic is open six days a week. Walk-in appointments are available every morning.</p>
<button id="show-hours" type="button">Show this week's hours</button>
<p id="hours" hidden>Monday to Friday 08:00 to 18:00. Saturday 09:00 to 13:00.</p>
</main>
<script>
// A notice that arrives after the page has drawn, pushing everything down
setTimeout(() => {
const notice = document.createElement('p')
notice.className = 'notice'
notice.textContent = 'Flu vaccinations are available every Saturday this month.'
document.getElementById('notice-slot').append(notice)
}, 600)
// A click handler that keeps the main thread busy for 300 ms
document.getElementById('show-hours').addEventListener('click', () => {
const end = performance.now() + 300
while (performance.now() < end) {}
document.getElementById('hours').hidden = false
})
</script>
<script type="module" src="vitals.js"></script>
</body>
</html>
HTMLCheck it worked
First check that the collector accepts a report, the way a beacon would send it:
cd ~/web-vitals-demo
curl -s -o /dev/null -w '%{http_code}\n' -X POST --data '[{"name":"LCP","value":1234,"rating":"good","id":"check-1","navigationType":"navigate","page":"/"}]' http://127.0.0.1:8095/vitals
cat vitals.jsonl
rm vitals.jsonlIt prints 204, then one line with "name":"LCP" and "value":1234. The last command removes that made-up line, so only real visits count from here on.
Then make a real visit. Reload http://127.0.0.1:8095/ in Chrome, wait for the notice, click Show this week's hours, then switch to another tab. Run cat vitals.jsonl in the demo folder: there are three new lines, for LCP, INP and CLS, each with a value and a rating. CLS is only reported in Chromium-based browsers; Firefox and Safari send LCP and INP.
Step 5 · Simulate visits and read the field numbers
Field data only means something across many visits, so you summarise it as a percentile. Google's assessment uses the 75th percentile (p75): the value three in four visits beat. One very slow visit does not fail a page, but a slow quarter of visitors does.
You cannot hand this page to a thousand patients, so a Playwright script stands in for one. It opens the page on a phone-sized screen, waits for the notice, taps the button, and then sends the page its hidden signal. A headless browser has no tab to switch away from, so the script sets visibilityState to hidden and fires visibilitychange, the same event a phone sends when the visitor switches app. It launches with channel: 'chromium', the full Chromium build that Lighthouse also uses, rather than Playwright's default lightweight headless shell, so the browser measures the click the way a desktop Chrome would. Then it waits for the collector to write the three metrics:
cd ~/web-vitals-demo
cat > visit.mjs <<'JS'
import { chromium } from 'playwright'
import { readFile } from 'node:fs/promises'
import assert from 'node:assert/strict'
async function received() {
try {
const text = await readFile('vitals.jsonl', 'utf8')
return text.split('\n').filter(Boolean).map((line) => JSON.parse(line))
} catch {
return []
}
}
const seenBefore = (await received()).length
const browser = await chromium.launch({ channel: 'chromium' })
const page = await browser.newPage({ viewport: { width: 412, height: 823 } })
await page.goto('http://127.0.0.1:8095/', { waitUntil: 'load' })
await page.waitForSelector('.notice')
await page.waitForTimeout(1000)
await page.click('#show-hours')
await page.waitForSelector('#hours', { state: 'visible' })
await page.waitForTimeout(1000)
await page.evaluate(() => {
Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true })
document.dispatchEvent(new Event('visibilitychange', { bubbles: true }))
})
let mine = []
for (let i = 0; i < 50; i++) {
mine = (await received()).slice(seenBefore)
if (new Set(mine.map((m) => m.name)).size === 3) break
await page.waitForTimeout(100)
}
await browser.close()
for (const m of mine) console.log(`${m.name}: ${m.name === 'CLS' ? m.value.toFixed(3) : Math.round(m.value) + ' ms'} (${m.rating})`)
const byName = Object.fromEntries(mine.map((m) => [m.name, m]))
assert.ok(byName.LCP?.value > 0, 'LCP was received')
assert.ok(byName.CLS?.value > 0, 'CLS was received and the notice moved the page')
assert.ok(byName.INP?.value >= 250, 'INP was received and includes the 300 ms handler')
console.log('PASS: the collector received LCP, INP and CLS')
JS
for visit in 1 2 3; do node visit.mjs; doneThen summarise everything the collector has. The script keeps the last report for each id, takes the 75th percentile of each metric and rates it against the same thresholds the library uses:
cd ~/web-vitals-demo
cat > field-report.mjs <<'JS'
import { readFile } from 'node:fs/promises'
const thresholds = { LCP: [2500, 4000], INP: [200, 500], CLS: [0.1, 0.25] }
const lines = (await readFile('vitals.jsonl', 'utf8')).split('\n').filter(Boolean).map((line) => JSON.parse(line))
const lastPerView = new Map(lines.map((m) => [m.id, m]))
for (const [name, [good, poor]] of Object.entries(thresholds)) {
const values = [...lastPerView.values()].filter((m) => m.name === name).map((m) => m.value).sort((a, b) => a - b)
if (values.length === 0) {
console.log(`${name}: no data yet`)
continue
}
const p75 = values[Math.ceil(values.length * 0.75) - 1]
const rating = p75 <= good ? 'good' : p75 <= poor ? 'needs improvement' : 'poor'
const shown = name === 'CLS' ? p75.toFixed(3) : `${Math.round(p75)} ms`
console.log(`${name}: p75 ${shown} from ${values.length} page views, ${rating}`)
}
JS
node field-report.mjsCheck it worked
Each visit prints its three metrics and ends with PASS: the collector received LCP, INP and CLS. The summary shows p75 values from three or four page views (four if you made the visit by hand in the last step). INP comes out at something like 300 ms or more, rated needs improvement, because of the busy click handler, which Lighthouse's load report could not see. LCP is fast, because these visits load the 3 MB image from your own machine with no slow network in the way. That is the same page giving very different numbers in the lab and the field, which is why you keep both.
On a live site, you would store these rows in a database or send them to an analytics tool, and split them by page and device type. The Chrome UX Report (CrUX), which feeds the field section of PageSpeed Insights, publishes the same three metrics for popular sites from real Chrome users, so you can compare your own collector with it once you have traffic.
Step 6 · Fail a check when LCP goes over budget
A performance budget turns "the page feels slow" into a number a build can fail on. Lab data suits budgets: it is available on every change, before anyone visits. Write the budget as the good thresholds, and have a script read the Lighthouse JSON and exit with code 1 when any metric is over, which is what makes a CI job fail:
cd ~/web-vitals-demo
cat > check-budget.mjs <<'JS'
import { readFile } from 'node:fs/promises'
const budget = {
'largest-contentful-paint': 2500, // milliseconds
'cumulative-layout-shift': 0.1,
}
const report = JSON.parse(await readFile(process.argv[2], 'utf8'))
if (report.runtimeError) throw new Error(`Lighthouse could not finish: ${report.runtimeError.message}`)
let over = 0
for (const [id, limit] of Object.entries(budget)) {
const audit = report.audits[id]
const value = audit.numericValue
const ok = Number.isFinite(value) && value <= limit
if (!ok) over++
const shown = id === 'cumulative-layout-shift' ? value.toFixed(3) : `${Math.round(value)} ms`
console.log(`${ok ? 'PASS' : 'FAIL'} ${audit.title}: ${shown} (budget ${limit})`)
}
if (over > 0) {
console.log(`${over} metric(s) over budget`)
process.exitCode = 1
} else {
console.log('Within budget')
}
JSRun it on the report you already have, and print the exit code:
cd ~/web-vitals-demo
node check-budget.mjs lh-before.report.json || echo "exit code: $?"The script checks a report rather than running Lighthouse itself, so the same check works on a report from any machine. In a CI job, run the Lighthouse command from the earlier step against a preview of the site, then node check-budget.mjs on its JSON.
Check it worked
The output has a FAIL line for Largest Contentful Paint, at many seconds against a budget of 2500, then metric(s) over budget and exit code: 1. Cumulative Layout Shift probably fails too, from the late notice and from the image arriving without a reserved size.
Step 7 · Fix the page and pass the budget
Two changes fix the lab numbers. The page uses the small image at the size it is shown, with width and height so the browser reserves its space before it arrives and fetchpriority="high" so it is fetched early. The notice slot gets a min-height equal to the notice, so the notice fills space that was already there instead of pushing the page down. The slow button stays as it is: fixing INP is its own tutorial, linked at the end.
cd ~/web-vitals-demo
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>Opening hours · Larkfield Clinic</title>
<style>
body { margin: 0; font-family: system-ui, sans-serif; color: #1b1f24; background: #f6f7f8; }
main { max-width: 40rem; margin: 0 auto; padding: 1rem; }
.hero { display: block; width: 100%; height: auto; }
#notice-slot { min-height: 140px; }
.notice { box-sizing: border-box; height: 140px; margin: 0; padding: 1rem; background: #0f5e5a; color: #ffffff; }
button { min-height: 48px; padding: 0 1rem; font: inherit; }
</style>
</head>
<body>
<div id="notice-slot"></div>
<main>
<h1>Opening hours</h1>
<img class="hero" src="hero-small.png" width="600" height="400" fetchpriority="high" alt="">
<p>Larkfield Clinic is open six days a week. Walk-in appointments are available every morning.</p>
<button id="show-hours" type="button">Show this week's hours</button>
<p id="hours" hidden>Monday to Friday 08:00 to 18:00. Saturday 09:00 to 13:00.</p>
</main>
<script>
// The notice now fills a slot that already has its height
setTimeout(() => {
const notice = document.createElement('p')
notice.className = 'notice'
notice.textContent = 'Flu vaccinations are available every Saturday this month.'
document.getElementById('notice-slot').append(notice)
}, 600)
// A click handler that keeps the main thread busy for 300 ms
document.getElementById('show-hours').addEventListener('click', () => {
const end = performance.now() + 300
while (performance.now() < end) {}
document.getElementById('hours').hidden = false
})
</script>
<script type="module" src="vitals.js"></script>
</body>
</html>
HTMLRun Lighthouse again into a new report, so you keep the "before" one for comparison:
npx lighthouse http://127.0.0.1:8095/ --only-categories=performance --output=json --output=html --output-path=./lh-after --chrome-flags="--headless" --quietThen read it and check the budget:
cd ~/web-vitals-demo
node read-report.mjs lh-after.report.json
node check-budget.mjs lh-after.report.jsonCheck it worked
read-report.mjs shows a much higher score than before and a simulated LCP well under 2.5 s. check-budget.mjs prints two PASS lines and Within budget, and exits with code 0: run echo $? straight after it and you see 0. Run node visit.mjs once more: it prints CLS as 0.000 for the new view and then stops with an AssertionError on CLS, because its check was written for the page that jumped. INP in the same output is still around 300 ms, because the click handler has not changed.
Step 8 · Clean up
Stop the server with Ctrl+C in its terminal.
Playwright keeps its Chromium download, a few hundred megabytes, in a shared cache folder outside the project. Remove it from inside the demo folder, then delete the folder:
cd ~/web-vitals-demo
npx playwright uninstall
cd ~
rm -rf ~/web-vitals-demonpx playwright uninstall only removes browsers no other project on your machine still uses.
Check it worked
ls ~/web-vitals-demo reports that there is no such file or directory, and http://127.0.0.1:8095/ no longer loads.
Next steps
- Take LCP apart into its four phases and fix the slow one in improve Largest Contentful Paint.
- Fix the 300 ms click handler and bring INP under 200 ms in speed up slow interactions and improve INP.
- Measure the whole page weight on a throttled phone profile, with a byte budget, in test and speed up a page on a slow phone connection.
Part of these paths
Related tutorials
- 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.
- Test and speed up a page on a slow phone connectionYou 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.
- Speed up slow interactions and improve Interaction to Next PaintYou will take a filter box that freezes the page on every key press, measure each interaction's input delay, processing time and presentation delay, and fix it by batching layout reads and writes, yielding to the browser, chunking the work and debouncing it, until a scripted measurement on a slowed-down CPU shows the worst interaction under 200 ms.
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