Lesson 43 of 52Performance and tooling
Core Web Vitals and Page Speed
Measure and fix LCP, INP and CLS without a framework: field versus lab data, the LCP breakdown, layout shift scoring, the critical path, bfcache and prerendering.
Your pages now look right on every screen. This unit is about making them fast, and it is written at a working developer's level, with more numbers and tools than the units before it. Monday morning, the marketing lead forwards a Search Console email: "Core Web Vitals issues detected: 1,240 mobile URLs are Poor." You run Lighthouse on your laptop and get 96. Both are telling the truth, and knowing why is the first skill this lesson teaches. Page speed is one of the few frontend topics with hard numbers attached: it affects conversion, bounce rate and search ranking, and performance work is easy to show in a portfolio or an interview because the before and after are measurable. This lesson is framework-neutral and focuses on HTML, CSS and how the browser loads a page. The JavaScript side (long tasks, workers, memory) is in Performance and Memory in the Browser, and the Next.js specifics are in Performance and Bundle Size in Next.js.
The three metrics and how they are judged
Google's Core Web Vitals are three user-centred metrics. Each answers a question a user would ask.
| Metric | The user's question | Good | Needs improvement | Poor |
|---|---|---|---|---|
| LCP Largest Contentful Paint | Is the main content here yet? | 2.5 s or less | up to 4 s | over 4 s |
| INP Interaction to Next Paint | Does it react when I tap? | 200 ms or less | up to 500 ms | over 500 ms |
| CLS Cumulative Layout Shift | Does it stay still? | 0.1 or less | up to 0.25 | over 0.25 |
The rules for judging matter as much as the numbers:
- Each metric is assessed at the 75th percentile of real page loads, separately for mobile and desktop. A page passes only if 75% of visits are good. A great median with a slow tail fails.
- To pass Core Web Vitals, a page must be good on all three.
- INP replaced First Input Delay (FID) on 12 March 2024. FID only measured the delay before the first interaction's handler started. INP measures the whole time from input to the next painted frame, for clicks, taps and key presses (not hover or scroll), across the whole visit. It reports roughly the worst interaction, ignoring one outlier per 50 interactions on very busy pages. If you read an article that tunes FID, it is out of date.
Supporting metrics help you diagnose. TTFB (Time to First Byte) is how long the server and network took to start sending HTML. FCP (First Contentful Paint) is when anything appears. TBT (Total Blocking Time) adds up the part of every main-thread task over 50 ms between FCP and the page becoming interactive. TBT exists because a lab run has no real user tapping, so it cannot measure INP. TBT is its lab stand-in.
Field data versus lab data
Field data, also called RUM (real user monitoring), comes from real visitors. Google's version is CrUX, the Chrome User Experience Report: anonymised measurements from Chrome users who opted in, aggregated over a rolling 28-day window. PageSpeed Insights shows it in the top section ("Discover what your real users are experiencing"), and Search Console groups URLs that look alike and reports them as Good, Needs improvement or Poor. This is the data search ranking uses.
Lab data comes from one controlled run: Lighthouse, the DevTools Performance panel, WebPageTest. It is repeatable and gives you a trace to dig into, so it is the tool for finding why. The Lighthouse score itself is a weighted blend of lab metrics, not a Core Web Vital.
They disagree for predictable reasons, and you should be able to list them:
- Devices and networks. Your laptop and office Wi-Fi are far faster than the p75 user's phone on mobile data. Lighthouse simulates a mid-range phone, but only roughly.
- Cache state. Lighthouse loads cold. Real users often have your CSS cached, or arrive via the back button.
- The page they saw. Field users hit cookie banners, A/B test variants, personalised content and ads that a clean lab run never sees.
- Time. Lab data is now. CrUX is the last 28 days, so a fix takes weeks to show fully.
- Interactions and scrolling. CLS in the field keeps counting while users scroll and the page lazy-loads; INP needs real taps. A lab load sees neither.
The workflow follows: field data tells you which pages and which metric are failing, lab tools tell you why, and field data confirms the fix. To collect your own field data, Google's small web-vitals library reports each metric once it is final, and its attribution build adds the cause: the LCP element and its breakdown, the element that shifted, the script behind a slow interaction.
import { onLCP, onINP, onCLS } from "web-vitals/attribution";
function send({ name, value, rating, attribution }) {
const body = JSON.stringify({
name, value, rating, page: location.pathname,
// LCP: which element; CLS: which element shifted most; INP: which element was tapped
target: attribution.target ?? attribution.largestShiftTarget ?? attribution.interactionTarget,
});
navigator.sendBeacon("/rum", body); // survives the tab closing
}
onLCP(send);
onINP(send);
onCLS(send);LCP in four parts
LCP is the render time of the largest image, video poster or text block visible in the viewport. Background images from CSS url() count; gradients, invisible elements and full-viewport backgrounds do not. Chromium stops looking for new candidates once the user taps, scrolls or presses a key. On most sites the LCP element is the hero image or the main heading.
You cannot fix "LCP is 3.8 s". You can fix one of its four parts:
TTFB: nothing can happen before the HTML starts arriving. Fix with caching, a CDN, fewer redirects, and not waiting on slow queries before sending the first byte. Aim for roughly 40% of LCP at most.
The rough targets (40%, under 10%, 40%, under 10%) are web.dev's guidance, not rules. The point is that the two "delay" parts should be near zero, because they are pure waste. Here is the breakdown arithmetic from a real-looking trace:
Press Run (⌘ Enter) to see what happens.A 1,280 ms load delay says the browser found the hero image late. The usual causes and fixes:
<!-- Bad: the image is only found after CSS downloads and layout runs -->
<div class="hero" style="background-image: url(hero.avif)"></div>
<!-- Bad: lazy loading the LCP image delays its request on purpose -->
<img src="hero.avif" loading="lazy" alt="...">
<!-- Good: in the HTML, high priority, real dimensions -->
<img src="hero.avif" fetchpriority="high" width="1600" height="900" alt="...">
<!-- If it must stay a CSS background, tell the preload scanner about it -->
<link rel="preload" as="image" href="hero.avif" fetchpriority="high">The preload scanner is a second, lightweight parser that races ahead through the raw HTML looking for resources to fetch while the main parser is blocked. It sees <img src>, <link> and <script src>. It does not see CSS backgrounds, images inserted by JavaScript, or data-src attributes swapped in by a lazy-loading script. Making the LCP resource visible to the preload scanner is the single most common LCP fix. Use fetchpriority="high" on one or two images at most: when everything is high priority, nothing is. fetchpriority is supported in all current major browsers.
<img> in the HTML. What is the most likely cause?CLS: how layout shift is scored
A layout shift happens when a visible element changes its start position between frames without the user causing it. Each shift gets a score:
layout shift score = impact fraction × distance fraction
The impact fraction is how much of the viewport the moving elements cover, before and after combined. The distance fraction is how far the furthest one moved, divided by the viewport's larger dimension. An element covering 75% of the viewport that moves down by 25% of the viewport height scores 0.75 × 0.25 = 0.1875: one shift like that fails the page on its own.
Shifts are then grouped into session windows: a window keeps growing while shifts arrive less than 1 second apart, up to 5 seconds long. CLS is the score of the worst window, not the sum of every shift over the visit. That is why a long-lived single-page app is not punished just for being open a long time. Shifts within 500 ms of a tap, click or key press are excluded (they carry hadRecentInput: true), because a user expects the page to change when they act. Scrolling does not count as input.
Press Run (⌘ Enter) to see what happens.Without the recentInput flag, the shift at 2,100 ms would count. What would CLS be then?
// same shifts, but { t: 2100, score: 0.09 } now counts
// window rule: gap < 1000 ms, window < 5000 ms
// CLS = worst windowYou can watch shifts happen in Chromium (Chrome, Edge) with a PerformanceObserver for layout-shift entries, which is exactly what the web-vitals library uses underneath. This demo inserts a banner on a timer, then moves two boxes: one by animating margin-left, one by animating transform. The preview restarts every time you edit the code.
Preview
Now fix it: add #slot { min-height: 80px; } to the style block. The banner fills space that was already reserved, nothing below it moves, and its shift disappears. That is the whole CLS playbook: reserve space before content arrives. Notice also that the transform box never appears in the log, while the margin-left box shifts on every frame of its animation.
- Images and video without dimensions. Set
widthandheightattributes, oraspect-ratioin CSS, so the box exists before the bytes do (from Images and Media). - Injected content above existing content: cookie banners, ads, "download our app" bars, late-loading embeds. Reserve a fixed slot with
min-height, overlay it (position: fixedbanners do not shift content), or insert it below the viewport. - Web fonts swapping in with different metrics, which reflows every line. The fix is fallback metric matching, covered in Loading Fonts and Images Fast.
- Animating layout properties. Animating
top,heightormarginmoves other elements and counts as shifts. Animatetransforminstead, which never triggers a layout shift.
INP from the HTML and CSS side
INP is made of input delay (the main thread was busy when the tap arrived), processing time (your event handlers) and presentation delay (style, layout and paint for the next frame). Performance and Memory in the Browser covers the JavaScript fixes: breaking up long tasks over 50 ms, yielding with scheduler.yield() where supported (Chromium; feature-detect and fall back to setTimeout), and moving work to workers.
HTML and CSS own most of the presentation delay. The cost of style and layout grows with how many elements are affected, so a 15,000-node DOM makes every interaction slower even if your handler is tiny. Cut the DOM (paginate, virtualise long lists, do not render hidden tabs and menus until opened), and use content-visibility: auto on long, independent sections. The browser skips layout and paint for those sections until they approach the viewport. Pair it with contain-intrinsic-size so skipped sections keep an estimated height and the scrollbar does not jump. It has been Baseline since 2024.
Preview
Click each button a few times. The auto version skips layout for the thousands of offscreen sections, so the forced layout is several times faster. Real pages see the same effect on their first render and on any interaction that changes styles.
The critical rendering path
Before the first paint, the browser needs the HTML and all render-blocking resources: every stylesheet in the <head> (CSS blocks rendering, because painting unstyled content then restyling it would be worse) and every classic <script> without defer or async (it blocks the parser, because the script might call document.write or read the DOM above it).
| Script | Downloads | Runs | Order kept | Use for |
|---|---|---|---|---|
<script src> | Blocks the parser | Immediately | Yes | Almost nothing in the head |
<script defer> | In parallel | After parsing, before DOMContentLoaded | Yes | Your app code |
<script async> | In parallel | As soon as it arrives, pausing the parser | No | Independent scripts like analytics |
<script type="module"> | In parallel | Deferred by default | Yes | Modern app code with import |
Put the browser's steps for a first page load in order.
- Tap the steps below in the right order.
Practical rules: keep head CSS small, load app scripts with defer or type="module", and add <link rel="preconnect" href="https://cdn.example.com"> for one or two critical third-party origins, which does the DNS, TCP and TLS setup early. Inlining critical CSS (the rules needed for the first screen, in a <style> tag, with the rest loaded later) can cut a round trip on slow connections, but the inlined CSS is never cached and must be regenerated whenever styles change. It is worth it for content sites with a slow first visit, and rarely for an app whose users come back daily.
Instant navigations: bfcache and prerendering
The fastest page load is one that does not happen. The back/forward cache (bfcache) keeps a full snapshot of a page in memory when the user leaves, so the back button restores it instantly with near-zero LCP. Pages lose eligibility for common reasons: an unload event handler (use pagehide instead), and in some browsers Cache-Control: no-store on the HTML. DevTools has a check under Application, "Back/forward cache", that lists exactly what blocks your page. If your code needs to refresh state on restore, listen for pageshow and check event.persisted.
Speculation Rules let Chromium browsers prefetch or fully prerender a likely next page in the background, so it appears instantly on click:
<script type="speculationrules">
{
"prerender": [{
"where": { "and": [
{ "href_matches": "/*" },
{ "not": { "href_matches": "/logout" } },
{ "not": { "selector_matches": ".no-prerender" } }
]},
"eagerness": "moderate"
}]
}
</script>moderate starts when the user hovers a link briefly, which balances wins against wasted work. Exclude URLs with side effects (log out, add to cart), and remember prerendered pages run their scripts, so analytics must not count a page view until it is actually shown. Other browsers ignore the script tag, so it is safe progressive enhancement. Check MDN for current support before relying on it.
Budgets and Lighthouse CI
Sites rarely get slow in one commit. They get slow through fifty reasonable ones. A performance budget turns "keep it fast" into a check that fails the build: a maximum LCP or TBT in lab runs, a maximum kilobytes of JavaScript or images per page. Lighthouse CI runs Lighthouse several times against a preview build and asserts your budgets:
{
"ci": {
"collect": { "url": ["http://localhost:3000/", "http://localhost:3000/pricing"], "numberOfRuns": 3 },
"assert": {
"assertions": {
"largest-contentful-paint": ["error", { "maxNumericValue": 2500 }],
"cumulative-layout-shift": ["error", { "maxNumericValue": 0.1 }],
"total-blocking-time": ["warn", { "maxNumericValue": 200 }],
"resource-summary:script:size": ["warn", { "maxNumericValue": 170000 }]
}
}
}
}npx @lhci/cli autorunRun several times and use the median, since single lab runs are noisy. Lab budgets catch regressions before release, and field dashboards by page template show what users actually got.
- p75
- The 75th percentile of real page loads. Core Web Vitals pass when the p75 value is within the good threshold.
- CrUX
- Chrome User Experience Report: Google's field data from opted-in Chrome users over a rolling 28 days, used for search.
- LCP subparts
- TTFB, resource load delay, resource load duration and element render delay, which add up to LCP.
- preload scanner
- A fast secondary parser that finds resources in raw HTML and starts fetching them while the main parser is blocked.
- session window
- A burst of layout shifts under 1 s apart, up to 5 s long. CLS is the score of the worst window.
- render-blocking
- A resource, usually head CSS or a synchronous script, that must finish before the browser paints.
- bfcache
- The back/forward cache: a full in-memory snapshot of a page that makes back and forward navigation instant.