# Performance

> Measure LCP, INP, and CLS in the field, reproduce the slow page in Lighthouse, fix each metric, precache the shell, and guard the result with Lighthouse CI.

Core Web Vitals measure loading and responsiveness as well as layout stability. Aim for field values
at or under LCP 2.5 s and INP 200 ms. Aim for CLS 0.1 or under. Use the 75th percentile
of page loads for each metric.
Cache the shell for repeat launches and configure CI to fail the build when a metric
goes over its limit. Measure, fix the largest problem, and measure again.

You need the production build and a place to send telemetry, plus a mid-range phone or Chrome's CPU and
network throttling. The metric definitions live in
[Core Web Vitals for PWAs: LCP, INP, and CLS](/reference/performance/core-web-vitals/).

## Collect field data with web-vitals

Lab tools cannot see what real users experience on their devices, and the Chrome User
Experience Report can tell you that a page or origin has a problem but not what caused it, so instrument
the page. The `web-vitals` library (Apache 2.0) wraps the underlying browser APIs and
reports each metric when it is ready; `onCLS` and `onINP` can fire more than once, for
example when the page is hidden, so the backend should keep the last value per `id`.

```js
import { onCLS, onINP, onLCP } from 'web-vitals/attribution';

function report(metric) {
  const body = JSON.stringify({
    name: metric.name, // 'LCP' | 'INP' | 'CLS'
    value: metric.value,
    rating: metric.rating, // 'good' | 'needs-improvement' | 'poor'
    id: metric.id,
    target:
      metric.attribution?.target ??
      metric.attribution?.largestShiftTarget ??
      metric.attribution?.interactionTarget ??
      null,
    path: new URL(metric.navigationURL ?? location.href).pathname,
  });
  (navigator.sendBeacon && navigator.sendBeacon('/vitals', body)) ||
    fetch('/vitals', { body, method: 'POST', keepalive: true });
}

onCLS(report);
onINP(report);
onLCP(report);
```

The `attribution` build adds about 1.5 KB (Brotli) over the standard build and tells you
which element was the LCP candidate or which interaction was the slowest. Aggregate per path, then read the 75th percentile,
split by mobile and desktop.

## Reproduce the slow page in Lighthouse

Open Chrome DevTools, choose the **Lighthouse** panel, and run a mobile audit against the
production URL that your field data flags. Lighthouse measures LCP and CLS but not INP: a
lab run loads the page without interacting, so Total Blocking Time stands in as a proxy.
Lighthouse also scores desktop more strictly than the field thresholds (LCP under 1.2 s
is green on desktop against 2.5 s on mobile), so compare lab numbers with lab numbers.

:::note
Chrome's [Lighthouse LCP audit documentation](https://developer.chrome.com/docs/lighthouse/performance/lighthouse-largest-contentful-paint) says Lighthouse displays the LCP element along with a subpart breakdown in the "Largest Contentful Paint element" diagnostic, with the subparts TTFB, load delay, load time, and render delay. The score bands documented for that audit are 0 to 2.5 s (green), 2.5 to 4 s (orange), and over 4 s (red) on mobile, and 0 to 1.2 s, 1.2 to 2.4 s, and over 2.4 s on desktop.
:::

## Shrink LCP

The LCP element is often a hero image or a block of text; [web.dev](https://web.dev/articles/lcp) lists the element types that can qualify. For an image, give it an explicit `fetchpriority="high"` and a `<link rel="preload">`, serve it as AVIF or
WebP at the rendered size, and keep render-blocking stylesheets and scripts off the
path to it ([Optimize LCP](https://web.dev/articles/optimize-lcp)). For fonts, `font-display: swap` paints text in the fallback face at once at the
cost of a visible swap; `optional` gives the font no swap period, so a late font may not show on that visit
([font-display](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display)).

```html
<link rel="preload" as="image" href="/hero-1200.avif" imagesrcset="/hero-800.avif 800w, /hero-1200.avif 1200w" imagesizes="100vw">
<img src="/hero-1200.avif" srcset="/hero-800.avif 800w, /hero-1200.avif 1200w" sizes="100vw" width="1200" height="600" fetchpriority="high" alt="">
```

## Shrink INP

INP is the latency of the slowest click, tap, or key press over the page's life (one
outlier per 50 interactions discarded), measured from input to the next frame. Long tasks
on the main thread are a common cause. Split work with [`scheduler.yield()`](https://developer.mozilla.org/en-US/docs/Web/API/Scheduler/yield) where it exists
and `setTimeout(resolve, 0)` where it does not, defer non-critical JavaScript, and keep the
handler's own work small so the browser gets a chance to paint before the expensive part runs.

```js
async function onFilterChange(event) {
  renderSpinner(); // cheap: paint feedback first
  await yieldToMain();
  applyFilter(event.target.value); // expensive: runs after yielding, usually after a paint
}

function yieldToMain() {
  if ('scheduler' in globalThis && 'yield' in scheduler) return scheduler.yield();
  return new Promise((resolve) => setTimeout(resolve, 0));
}
```

## Shrink CLS

Reserve space for everything that arrives late ([Optimize CLS](https://web.dev/articles/optimize-cls)): `width` and `height` attributes on images
and videos, `aspect-ratio` on embeds, a fixed-height container for ads and consent banners,
and `min-height` on content that streams in. Animate with `transform` rather than
`top`/`left`, which do not count as layout shifts.

## Precache the shell for repeat launches

A shell precached by the service
worker can paint without a network round trip, installed or not. Follow [Offline strategies](/guides/offline/)
to precache HTML, CSS, and JavaScript, then measure LCP on the second launch separately
from the first visit; the first visit still requires the network load.

## Guard the gain with Lighthouse CI

Add a budget to fail the build when a metric goes over its limit.
Lighthouse CI runs Lighthouse against a static build or a started server and asserts on
audits.

```js
// lighthouserc.js
module.exports = {
  ci: {
    collect: { staticDistDir: './dist' },
    assert: {
      preset: 'lighthouse:recommended',
      assertions: {
        'largest-contentful-paint': ['error', { maxNumericValue: 2500 }],
        'cumulative-layout-shift': ['error', { maxNumericValue: 0.1 }],
      },
    },
    upload: { target: 'temporary-public-storage' },
  },
};
```

Install with `npm install -g @lhci/cli` and run `lhci autorun` in CI. The temporary public
storage target is the simplest upload; reports there are public and expire, so switch to
an LHCI server for private projects. A passing run is a lab result; the field numbers from step 1 show whether
real users benefit once new traffic has accumulated.

## See also

- [Core Web Vitals for PWAs: LCP, INP, and CLS](/reference/performance/core-web-vitals/)
- [Startup performance: paint and navigation timings](/reference/performance/startup-performance/)
- [Offline strategies](/guides/offline/)
- [Web Vitals](https://web.dev/articles/vitals) (web.dev)
- [Interaction to Next Paint (INP)](https://web.dev/articles/inp) (web.dev)
- [web-vitals](https://github.com/GoogleChrome/web-vitals) (github.com)

← Back to the [Guides](/guides/) overview.