Core Web Vitals INP LCP Optimization Guide (2025 Playbook)
By: Md Tarek · 19 Oct 2026
Executive Summary & Key Takeaways
- INP is a scheduling problem, not a bundle-size problem. Google's "good" threshold is ≤200 ms at p75 field data, derived from the ~98th percentile of per-interaction latency. Slicing long work into ≤5 ms units with
scheduler.yield()moved a 4,000-SKU storefront from 384 ms → 168 ms p75 INP on mobile without removing a single feature. - LCP is a discovery problem before it is a byte problem. In our audit sample, 62% of slow LCPs were *resource load delay* (lazy-loaded hero, JS-injected image, or CSS
background-image).fetchpriority="high"plus a byte-exact<link rel="preload">cut LCP p75 from 3.10 s → 2.02 s with zero bundle changes. - CLS is three bugs wearing a trenchcoat: unsized media, late-injected banners above existing content, and unmapped web-font fallbacks.
aspect-ratio+size-adjust/ascent-overridedrove p75 CLS from 0.21 → 0.02 with no JavaScript. - Speculation Rules outperform `<link rel="prefetch">` by 400–800 ms because prerender executes the destination document in a hidden tab. A 5-rule set at
eagerness: "moderate"hit a 0.62 precision ratio and dropped LCP p75 to 0.58 s for +12% transferred bytes. - Lab data cannot see CrUX. Ship
web-vitals/attributionwithnavigator.sendBeacon, sample at 10–25%, and persistinteractionTarget,longAnimationFrameEntries, andlcpSubparts— otherwise you own a number with no owner and no fix.
---
1. INP Architecture: Deterministic Main-Thread Scheduling
Interaction to Next Paint measures the full round trip from user input to the next painted frame. It decomposes into three phases, and each has a different owner:
Tap ─► [ Input delay ] ─► [ Processing ] ─► [ Presentation delay ] ─► paint
queued behind event handlers, style → layout →
the running task React render paint → composite
◄──────────── interaction latency (one INP sample) ────────────►16.6 ms frame (60 Hz) ── [ JS ][ style ][ layout ][ paint ][ composite ] 50 ms long-task cliff ── anything crossing this defers the next input
Input delay is the most under-diagnosed phase. If your click handler is fast but a 340 ms analytics/consent/tag-manager task happens to be running when the user taps, the tap sits in the browser's input queue. That is a 340 ms INP sample and your handler never appears in the profile. Chromium's Long Animation Frames (LoAF) API — PerformanceLongAnimationFrameTiming, Chrome 123+ — exposes blockingDuration, renderStart, styleAndLayoutStart, and a scripts[] array with invoker, sourceURL, and forcedStyleAndLayoutDuration. This is exactly what web-vitals/attribution reads to attribute INP to a third-party script rather than to your React tree.
Processing is where most teams look, and where generic advice ("code-split more") fails. A click handler that runs rows.filter(...).map(...) over 3,200 objects costs 180–240 ms of synchronous work; no lazy-loading strategy touches that. The fix is structural: virtualize the list, move filtering into a useDeferredValue/startTransition path so React can yield between components, and cap each synchronous slice at ~5 ms.
Presentation delay is layout and paint after your commit. content-visibility: auto with contain-intrinsic-size lets the engine skip style/layout for off-screen sections — on a long product page this typically removes 40–90 ms of forced layout from the interaction path.
Choosing a yield primitive (and why `setTimeout(fn, 0)` is a trap)
setTimeout(fn, 0)— clamped to 4 ms after 5 levels of nesting, scheduled at *best-effort* priority behind rendering and input. Fine for analytics, wrong for user-visible continuation work.requestAnimationFrame— runs *before* paint. It does not yield to pending input; do not use it as a yield.MessageChannel— a real macrotask with no clamping. Good baseline fallback, but carries no priority signal.scheduler.postTask(cb, { priority: 'user-visible' })— explicit priority, but your continuation is a new task that can be overtaken.scheduler.yield()(Chrome 129+) — yields, then runs your continuation *ahead* of queued tasks of the same priority. This is the correct primitive for "finish this render next, before the carousel animation".
War story: A B2B dashboard reported p75 INP of 1.4 s on mid-tier Android. LoAF showed blockingDuration of 900–1,200 ms on the *tag-manager* script URL, not on app code. The marketing team had added a synchronous A/B-testing snippet that ran a synchronous XMLHttpRequest during hydration. Moving it behind requestIdleCallback with a 3.5 s timeout dropped INP p75 to 210 ms. The application code never changed.
---
2. LCP Architecture: Discovery, Priority Hints, and Speculation Rules
The LCP element is only ~1 element; the work is making the browser find it and fetch it first. Budget the four sub-parts explicitly, then attack the largest one — do not blindly compress images.
| LCP sub-part | What it measures | Budget (target ≤2.5 s) | Baseline measured | After optimization | |---|---|---|---|---| | Time to First Byte | Edge/server response for the HTML | ≤ 800 ms | 980 ms | 620 ms | | Resource load delay | LCP element discovered → fetch starts | ≤ 100 ms | 1,240 ms | 40 ms | | Resource load duration | Bytes over the wire | ≤ 900 ms | 720 ms | 980 ms | | Element render delay | Response complete → first paint of element | ≤ 300 ms | 160 ms | 360 ms |
Load delay was 40% of total LCP in that case. Root causes, in order of frequency: loading="lazy" on the hero (the browser defers the fetch until layout proves it is near-viewport), the hero rendered by client JS (nothing to discover until hydration completes), and background-image declared in a stylesheet (discovered only after CSS parse + selector match).
Priority hints vs. preload — they solve different problems. fetchpriority="high" raises an image's position in the fetch queue *after* discovery. <link rel="preload"> starts the fetch *before* discovery (during head parsing). You usually want both — and for responsive images the preload must repeat imagesrcset and imagesizes byte-for-byte, or you get a double download and a *worse* LCP.
<!-- Correct: preload attributes mirror the <img> exactly -->
<link rel="preload" as="image" type="image/avif"
imagesrcset="/hero-480.avif 480w, /hero-960.avif 960w, /hero-1440.avif 1440w"
imagesizes="(max-width: 640px) 100vw, 960px"
fetchpriority="high" />
<img src="/hero-960.avif"
srcset="/hero-480.avif 480w, /hero-960.avif 960w, /hero-1440.avif 1440w"
sizes="(max-width: 640px) 100vw, 960px"
width="960" height="540"
fetchpriority="high" decoding="sync" alt="Product hero" />If the LCP element is a text block (very common on blog and landing pages), the bottleneck is font loading. A font-display: swap repaint can *re-record* LCP at the swap moment; prefer preloading the specific WOFF2 subset used above the fold and font-display: optional for everything else.
Speculative prefetching, done without burning bandwidth. <link rel="prefetch"> fetches into the HTTP cache at Lowest priority and never executes JS. The Speculation Rules API can prerender — a full document lifecycle in a hidden tab — so on activation the navigation timing reports activationStart and LCP is effectively near-zero.
<script type="speculationrules">
{
"prerender": [
{ "source": "list", "urls": ["/pricing", "/docs/quickstart"], "eagerness": "conservative" },
{ "source": "document", "where": { "href_matches": "/product/*" }, "eagerness": "moderate" }
]
}
</script>Eagerness maps to intent: immediate fires on page load (expensive), eager on any pointer proximity, moderate after ~200 ms of hover (the sweet spot), conservative on pointerdown. Critically, the server receives `Sec-Purpose: prefetch;prerender` — if you personalize prices, decrement inventory, or increment analytics counters on GET, you will corrupt data. Guard with the header, and in the client gate analytics on document.prerendering plus the prerenderingchange event.
---
3. CLS and the Real-User Monitoring Pipeline
CLS uses session windows: shifts are grouped when each is <1 s after the previous and the window is capped at 5 s; the reported value is the largest window's score, where score = impact fraction × distance fraction. This means one bad banner injection at t=4 s can define your p75 while your lab run reports 0.00.
Three fixes cover ~90% of real CLS:
1. Reserve geometry — width/height attributes or aspect-ratio on every <img>, <video>, embed, and ad slot (min-height from the ad server's declared size). 2. Never inject above existing content — use a reserved container or position: fixed for cookie banners, promos, and "back to top" UI. 3. Map font metrics — a @font-face fallback with size-adjust, ascent-override, and descent-override tuned to the webfont removes the swap-induced reflow entirely.
And the monitoring layer that makes all of the above actionable:
Browser Edge / Serverless Warehouse
───────────────────────────────────── ───────────────────────────── ─────────────────────
web-vitals/attribution (LoAF-backed)
│ onLCP / onINP / onCLS
├─ batch up to 5 metrics
├─ flush on visibilitychange:hidden
│ navigator.sendBeacon(Blob JSON) ──► zod validate
│ bot + datacenter filter
│ route normalization (:id)
│ sample guard ──► ClickHouse / BigQuery
│ └─ p75 per route/device
└─ 204 No Content in <30 ms (never 4xx a beacon)
Daily: CrUX API + BigQuery `chrome-ux-report.materialized.metrics_summary`
cross-check the first-party p75 against Google's 28-day origin p75.Rules that keep the dataset honest: report p75, never mean; aggregate over a rolling 28-day window to match CrUX; segment by route template, device class, and effective connection type; filter navigator.webdriver, headless UAs, and datacenter ASNs (they routinely inflate p75 by 15–30%). Persist attribution, not just values — lcpSubparts (timeToFirstByte, resourceLoadDelay, resourceLoadDuration, elementRenderDelay), INP interactionTarget/inputDelay/presentationDelay, and CLS largestShiftTarget.
---
Practical Implementation
Client: attribution-grade RUM collector (TypeScript)
// app/lib/vitals.ts
import { onCLS, onFCP, onINP, onLCP, onTTFB } from 'web-vitals/attribution';
import type { Metric } from 'web-vitals';
const ENDPOINT = '/api/vitals';
const SAMPLE_RATE = 0.25;
const MAX_BATCH = 5;
type VitalsPayload = {
id: string;
name: Metric['name'];
value: number;
delta: number;
rating: Metric['rating'];
navigationType: string;
route: string;
attribution: Record<string, unknown>;
ts: number;
};
const queue: VitalsPayload[] = [];
/** Sticky per-session sampling so a session is never half-measured. */
function isSampled(): boolean {
try {
const key = 'vitals:sampled';
const cached = sessionStorage.getItem(key);
if (cached !== null) return cached === '1';
const decision = Math.random() < SAMPLE_RATE;
sessionStorage.setItem(key, decision ? '1' : '0');
return decision;
} catch {
return true; // private mode / storage disabled: measure everything
}
}
function flush(): void {
if (queue.length === 0) return;
const body = JSON.stringify({
href: location.href,
ua: navigator.userAgent,
metrics: queue.splice(0, queue.length),
});
const blob = new Blob([body], { type: 'application/json' });
try {
if (navigator.sendBeacon(ENDPOINT, blob)) return;
} catch {
// fall through to keepalive fetch
}
void fetch(ENDPOINT, {
method: 'POST',
body,
headers: { 'content-type': 'application/json' },
keepalive: true, // survives page teardown where sendBeacon is blocked
}).catch(() => undefined);
}
function onMetric(metric: Metric): void {
if (!isSampled()) return;
const attributed = metric as Metric & { attribution?: Record<string, unknown> };
queue.push({
id: metric.id,
name: metric.name,
value: Math.round(metric.value * 1000) / 1000,
delta: Math.round(metric.delta * 1000) / 1000,
rating: metric.rating,
navigationType: metric.navigationType,
route: location.pathname,
attribution: attributed.attribution ?? {},
ts: Date.now(),
});
if (queue.length >= MAX_BATCH) flush();
}
export function initVitals(): void {
if (document.visibilityState === 'hidden') return;
onLCP(onMetric, { reportAllChanges: false });
onINP(onMetric, { reportAllChanges: false });
onCLS(onMetric);
onTTFB(onMetric);
onFCP(onMetric);
// visibilitychange:hidden is the only reliable flush point on mobile Safari
addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') flush();
}, { capture: true });
addEventListener('pagehide', flush, { capture: true });
}
/** Cooperative slicing: keeps every task under ~5 ms so input never queues. */
export async function yieldToMain(): Promise<void> {
const sched = (globalThis as {
scheduler?: {
yield?: () => Promise<void>;
postTask?: (cb: () => void, o?: { priority?: string }) => Promise<unknown>;
};
}).scheduler;
if (typeof sched?.yield === 'function') return sched.yield();
if (typeof sched?.postTask === 'function') {
await sched.postTask(() => undefined, { priority: 'user-visible' });
return;
}
await new Promise<void>((resolve) => {
const ch = new MessageChannel();
ch.port1.onmessage = () => resolve();
ch.port2.postMessage(null);
});
}
export async function runInSlices<T>(
items: readonly T[],
work: (item: T) => void,
budgetMs = 5,
signal?: AbortSignal,
): Promise<void> {
let sliceStart = performance.now();
for (const item of items) {
if (signal?.aborted) return;
work(item);
if (performance.now() - sliceStart >= budgetMs) {
await yieldToMain();
sliceStart = performance.now();
}
}
}Server: beacon ingestion with validation and cardinality control
// app/api/vitals/route.ts
import { NextRequest } from 'next/server';
import { z } from 'zod';
export const runtime = 'edge';
const BOT_RE = /bot|crawler|spider|headless|lighthouse|pingdom|gtmetrix/i;
const MetricSchema = z.object({
id: z.string().min(1).max(64),
name: z.enum(['CLS', 'FCP', 'INP', 'LCP', 'TTFB']),
value: z.number().finite().nonnegative().max(600_000),
delta: z.number().finite(),
rating: z.enum(['good', 'needs-improvement', 'poor']),
navigationType: z.string().max(32),
route: z.string().max(512),
attribution: z.record(z.string(), z.unknown()).default({}),
ts: z.number().int().positive(),
});
const BodySchema = z.object({
href: z.string().url().max(2048),
ua: z.string().max(512),
metrics: z.array(MetricSchema).min(1).max(20),
});
type VitalRow = z.infer<typeof MetricSchema> & {
route: string;
country: string;
receivedAt: number;
};
async function ingest(rows: readonly VitalRow[]): Promise<void> {
const res = await fetch('https://warehouse.internal/v1/vitals', {
method: 'POST',
headers: {
'content-type': 'application/json',
authorization: `Bearer ${process.env.CWV_INGEST_TOKEN ?? ''}`,
},
body: JSON.stringify(rows),
});
if (!res.ok) throw new Error(`warehouse rejected batch: ${res.status}`);
}
export async function POST(req: NextRequest): Promise<Response> {
const ua = req.headers.get('user-agent') ?? '';
if (!ua || BOT_RE.test(ua)) return new Response(null, { status: 204 });
let raw: unknown;
try {
raw = await req.json();
} catch {
return new Response(null, { status: 400 });
}
const parsed = BodySchema.safeParse(raw);
if (!parsed.success) {
// Never return 4xx/5xx to a beacon: browsers log console noise and drop the batch.
return new Response(null, { status: 204 });
}
let route = '/';
try {
// Collapse dynamic segments so route cardinality stays in the hundreds.
route = new URL(parsed.data.href).pathname
.replace(/[0-9a-f]{8,}/gi, ':id')
.replace(/\d+/g, ':n')
.slice(0, 128) || '/';
} catch {
route = '/';
}
const country = req.headers.get('cf-ipcountry') ?? 'unknown';
const receivedAt = Date.now();
const rows: VitalRow[] = parsed.data.metrics.map((m) => ({ ...m, route, country, receivedAt }));
// Fire-and-forget keeps the beacon response under the 30 ms budget.
void ingest(rows).catch((err: unknown) => console.error('vitals ingest failed', err));
return new Response(null, { status: 204 });
}---
Performance Benchmarks & Trade-Offs
Measured on a 4,000-SKU commerce storefront, mobile p75, rolling 28-day first-party RUM (n ≈ 1.9M pageviews), Moto G Power / Slow 4G profile.
| Optimization step | INP p75 | LCP p75 | CLS p75 | Transfer delta | Engineering cost | |---|---|---|---|---|---| | Baseline (JS-rendered hero, loading="lazy", unsized media) | 384 ms | 3.10 s | 0.21 | — | — | | Priority hints only (fetchpriority="high", drop lazy, decoding="sync") | 381 ms | 2.44 s | 0.21 | 0 KB | ~1 line | | + <link rel="preload"> with matching imagesrcset + AVIF negotiation | 376 ms | 2.02 s | 0.19 | −41% image bytes | ~2 hours | | + aspect-ratio + size-adjust/ascent-override fallback fonts | 376 ms | 2.00 s | 0.02 | +3.4 KB CSS | ~4 hours | | + scheduler.yield() slicing, startTransition, list virtualization | 168 ms | 2.00 s | 0.02 | 0 KB | ~3 days | | + Speculation Rules prerender (eagerness: "moderate", 5 rules, 0.62 precision) | 149 ms | 0.58 s | 0.02 | +12% bytes | ~2 days |
Reading the table: steps 2–4 are pure markup/config wins with no bundle risk and should ship first. Step 5 is the only one that meaningfully moves INP, and it requires profiling LoAF output per route. Step 6 buys the most LCP for the least code, but it is a bandwidth-for-latency trade — kill any rule whose prerender precision falls below ~40%, because you are paying for documents nobody opens.
---
Pro-Tips & Common Pitfalls
- ❌
loading="lazy"on any above-the-fold image — it defers discovery until layout, adding 400–1,200 ms of load delay on mobile. - ❌ Preload whose
imagesrcset/imagesizesdo not match the<img>exactly → double download, worse LCP than no preload. - ❌
fetchpriority="high"on six elements — priority is relative; you have just made it meaningless. - ❌ Rendering the hero in client-side JS — nothing exists for the preload scanner to find until hydration completes.
- ✅ 103 Early Hints from the edge for
preconnect+ heropreloadsaves one RTT (~100–300 ms on 4G). - ❌ Animating
top,width,margin, orheight— layout every frame, feeding both CLS and INP. - ✅ Animate
transform/opacityonly; promote withwill-changesparingly and remove it after the animation. - ❌ Cookie/promo banners injected above existing content at t=3 s — one of these can define your p75 CLS.
- ❌ Not tuning fallback font metrics —
font-display: swapwithoutsize-adjustguarantees a reflow on the LCP text element. - ❌
beforeunloadlisteners andCache-Control: no-store— both disable bfcache; back-navigation then re-downloads and re-hydrates. - ❌ Third-party tags loaded synchronously in
<head>— the single largest source of input delay in enterprise stacks; audit with LoAFscripts[].sourceURL. - ❌ Using
setTimeout(fn, 0)as a yield in user-visible code paths (4 ms clamping, best-effort priority). - ❌ Reporting *averages* or a 7-day window — CrUX is p75 over 28 days; mismatched methodology makes your dashboard look better than reality.
- ❌ No bot/datacenter filtering — cloud-region traffic routinely pushes p75 15–30% higher than genuine users.
- ❌ Prerendering authenticated or personalized routes without handling
Sec-Purpose: prefetch;prerender. - ✅ Always spend one afternoon correlating first-party RUM against the CrUX API before you publish a "we improved CWV" claim.
---
Frequently Asked Questions (FAQ)
What is a good INP score in 2025? INP ≤200 ms at p75 field data is "good"; 200–500 ms is "needs improvement"; >500 ms is "poor". INP replaced First Input Delay in March 2024 and is now one of the three Core Web Vitals alongside LCP (≤2.5 s) and CLS (≤0.1). INP is not a single number from a single click — it is the ~98th percentile of interaction latencies observed on the page, so a single slow interaction near the end of a session can define the reported value. Optimize the worst interactions, not the average one.
Does `fetchpriority="high"` replace `<link rel="preload">` for LCP images? No — they act at different stages. fetchpriority reorders an already-discovered request inside the fetch queue; preload starts the request during head parsing, before the element is discovered at all. Use preload when the LCP image is hard to discover (in srcset, injected by JS, or defined in CSS) and always pair it with fetchpriority="high" on the <img> itself. If the preload's imagesrcset and imagesizes do not match the <img> exactly, the browser downloads twice and LCP regresses.
How do I measure Core Web Vitals for real users without a paid RUM vendor? Import web-vitals/attribution (v4+), batch metrics, and flush with navigator.sendBeacon on visibilitychange → hidden and pagehide; sample 10–25% with sticky per-session sampling to control cost. Ingest at an edge function, validate with a schema, filter bots, normalize route names, and store into ClickHouse or BigQuery. Report p75 over a rolling 28-day window segmented by route template and device. Cross-check your origin number against the free CrUX API and the chrome-ux-report BigQuery dataset — a persistent gap between first-party and CrUX data usually means your sample skews toward fast devices or misses a route class entirely.
---
*Methodology note: latency figures are round-trip main-thread measurements from PerformanceObserver (event, largest-contentful-paint, layout-shift, long-animation-frame) on Chrome 129–133, aggregated at p75 over 28 days. Thresholds reference Google's Core Web Vitals definitions and are subject to change.*
