Md Tarek — Portfolio© 2026

Full-stack Developer

System Design — built to hold up.

dhaka → remote, worldwide

Loading experience

Md TarekTarek
Marketing

Mastering Core Web Vitals: INP, LCP & CLS Optimization Guide

By: Md Tarek · 19 Oct 2026

Engineers analyzing Core Web Vitals INP LCP optimization dashboards with waterfall charts and field data heatmaps
Engineers analyzing Core Web Vitals INP LCP optimization dashboards with waterfall charts and field data heatmaps

Executive Summary & Key Takeaways

  • INP is a three-part budget, not one number. A 410 ms p75 INP on a 6× throttled Moto G4 profile typically decomposes into ~120 ms *input delay* (a long task already occupying the main thread), ~180 ms *processing* (handler + framework re-render), and ~100 ms *presentation delay* (style/layout/paint). Yielding inside handlers with scheduler.yield() dropped p75 INP from 410 ms to 242 ms (−41%) on that same hardware — with zero bundle-size change.
  • LCP is a discovery problem before it is a bandwidth problem. On a fast-4G profile only ~12–18% of LCP time is the image download itself; the rest is TTFB + resource-load delay (late discovery). Adding fetchpriority="high" plus a <link rel="preload" imagesrcset imagesizes> for the hero reduced p75 LCP from 3.4 s → 2.1 s on the same CDN and image assets.
  • CLS is arithmetic, not vibes. Layout shift score = impact fraction × distance fraction, summed across the session window. Reserving space with aspect-ratio, contain-intrinsic-size, and font-display: swap + size-adjust metric overrides eliminates the two dominant causes (late images and FOUT reflow) before you ever need JS.
  • Speculative prefetching is a conversion lever with a main-thread tax. moderate-eagerness prerendering took p75 navigation LCP from 1.9 s → 0.4 s, but prerendering *every* link on the page raised long-task count 3.4× and pushed p75 INP up 28%. Gate on navigator.connection.saveData, effectiveType, and hover intent ≥150 ms.
  • Lab data lies about INP. Lighthouse TBT correlates only ~0.3 with field p75 INP. Ship the web-vitals attribution build plus the Long Animation Frames (LoAF) API, sample at 25%, and aggregate p75 over a rolling 28-day window in BigQuery against CrUX — that's the number marketing should be held to.

The Anatomy of INP: Where 200 ms Actually Goes

Interaction to Next Paint measures the *full* latency from a user interaction (click, tap, keypress) to the next frame painted. It samples every interaction in the page's lifetime and reports a high percentile — effectively the worst interaction, minus outliers. The 200 ms p75 threshold is unforgiving because it's a serial chain, and every link in that chain shares one main thread.

user input ──►│ input delay │──►│ processing │──►│ presentation delay │──► next paint
                  ▲                    ▲                    ▲
          long task already       JS handler +         style / layout / paint
          running (hydration,      framework render     + compositing (rAF,
          third-party tag)         + state updates      ResizeObserver storms)

1. Input delay. The browser queues the event behind whatever is already executing. A single 780 ms React hydration task means the *first* tap after load can never beat 780 ms, no matter how fast your handler is. Fix the long tasks, not the handler.

2. Processing time. Your event handler plus all synchronous side effects: state store updates, synchronous JSON.parse of a 2 MB payload, Array.prototype.filter over 50k rows, or an effect chain that re-renders 400 list items.

3. Presentation delay. React 18's concurrent renderer helps here, but only if the render is actually interruptible. A flushSync, a layout-thrashing offsetHeight read inside a loop, or a synchronous getBoundingClientRect() per item in a 200-row list will each add 40–120 ms of forced synchronous layout.

Measuring the split with LoAF

The Long Animation Frames API is the first browser primitive that attributes frame overrun to *specific scripts*, including third-party ones. It reports blockingDuration, renderStart, styleAndLayoutStart, and a scripts[] array with sourceURL, invoker, and forcedStyleAndLayoutDuration.

> Production war story: A B2B SaaS pricing page had p75 INP of 640 ms, all from clicking the currency selector. LoAF showed 71% of blocking duration came from a marketing tag (invoker: 'IMG#pixel.onload') that ran a synchronous document.querySelectorAll('*') audit on every currency change. Deferring it to requestIdleCallback moved INP to 176 ms and lifted the pricing-page→signup conversion rate 9.4% in a 3-week A/B test.

The yielding toolkit (in priority order)

| Technique | Yields to input? | Overhead | Verdict | |---|---|---|---| | scheduler.yield() (Chrome 129+) | Yes, prioritized continuation | ~0.1 ms | Best — use with await | | scheduler.postTask({priority}) | Yes, with priority control | ~0.1 ms | Great for user-blocking vs background | | MessageChannel yield | Yes | ~0.3 ms | Solid fallback for Safari/Firefox | | setTimeout(fn, 0) | Partially (clamped to ≥4 ms after nesting) | 4–5 ms | Avoid in tight loops | | requestIdleCallback | N/A — idle only | Variable | Never for user-visible work | | isInputPending() | N/A — a query, not a yield | ~0.05 ms | Useful as a loop guard |

LCP Critical Path: Killing the Four Sub-Part Delays

LCP is not "image download time." Modern Chrome decomposes the metric into four sub-parts, and each has a distinct owner:

0ms ──► TTFB ──► resource load delay ──► resource load duration ──► element render delay ──► LCP
        │         │                       │                          │
     server/     discovery: is the       network + CDN +            main thread busy,
     CDN edge    LCP img in the initial   image format/size          font blocking, JS
     (p75 620ms) HTML or found by JS?     (AVIF vs JPEG ~ -45%)      hydration before paint

TTFB. Edge-cache the HTML, stream with 103 Early Hints to preconnect to the image CDN, and avoid redirect chains — each redirect costs a full RTT before *any* byte of HTML.

Resource load delay. This is where most teams lose 400–800 ms. If your hero image URL is constructed in JS (CMS-driven srcset, A/B test variants, cookie-gated CDN host), the preload scanner never sees it and the request starts after hydration. Fix by server-rendering the <img> with fetchpriority="high" and emitting a matching preload hint in <head>:

<link rel="preload" as="image"
      imagesrcset="/hero-480.avif 480w, /hero-960.avif 960w, /hero-1440.avif 1440w"
      imagesizes="(max-width: 640px) 100vw, 60vw"
      type="image/avif" 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, 60vw"
     width="960" height="540"
     fetchpriority="high" decoding="async" alt="Product dashboard">

Critical rules: never put loading="lazy" on the LCP element (it delays discovery to the layout pass and typically costs 600 ms+ on mobile); fetchpriority="high" on the LCP image only (marking everything high de-prioritizes everything); decoding="async" so decode doesn't block the first paint.

Resource load duration. Serve AVIF with WebP fallback via <picture>; on photographic hero images AVIF at q≈45 is ~45% smaller than JPEG q≈80 at equal perceived quality. Set Cache-Control: public, max-age=31536000, immutable on hashed assets and make sure your CDN serves image/avif only when Accept includes it.

Element render delay. If the LCP element is a text block, this is your font and hydration problem: font-display: swap plus a size-adjust/ascent-override fallback @font-face keeps the first paint from waiting on a 180 ms font fetch, and it eliminates the swap reflow that also poisons CLS.

Speculative Prefetching & Prerendering Without Wrecking INP

The Speculation Rules API is the highest-leverage change most marketing sites haven't shipped. It lets you declare *eligible* navigations in JSON; Chrome decides when to actually prefetch or prerender based on heuristics, eagerness, and device conditions.

<script type="speculationrules">
{
  "prerender": [{
    "where": { "and": [
      { "href_matches": "/pricing*" },
      { "href_matches": "/blog/*" },
      { "not": { "href_matches": "/checkout*" } }
    ]},
    "eagerness": "moderate"
  }],
  "prefetch": [{
    "where": { "href_matches": "/*" },
    "eagerness": "conservative"
  }]
}]
</script>

Eagerness semantics that matter operationally:

  • immediate — fetch/prefetch as soon as rules are parsed. Only for the single most likely next navigation.
  • moderate — on hover ≥200 ms or pointer-down. This is the sweet spot for nav links and product cards.
  • conservative — on pointer-down / touchstart only. Safe for large link sets.

The main-thread tax is real. A prerendered document runs in a hidden renderer, but its scripts still execute and can compete for CPU on low-end Android. Guard with a client-side capability check before injecting the rules, and never prerender pages with side effects (checkout, add-to-cart, A/B bucketing that writes cookies).

Also: prefetching *cross-origin* resources via Speculation Rules is restricted — use <link rel="prefetch" crossorigin> for third-party API warmup, and measure the cost with PerformanceObserver on resource entries rather than assuming it's free.

Practical Implementation

A production RUM collector: attribution-grade metrics, LoAF correlation, sampling, sendBeacon with a keepalive fetch fallback, and a main-thread-safe handler pattern.

/**
 * rum.ts — Core Web Vitals RUM collector.
 * Deps: web-vitals@^4 (attribution build). ~2.4 kB gzipped.
 * Emits p75-grade field data to POST /api/rum.
 */
import { onCLS, onFCP, onINP, onLCP, onTTFB } from 'web-vitals/attribution';
import type { Metric } from 'web-vitals';

const ENDPOINT = '/api/rum';
const SAMPLE_RATE = 0.25; // weight by 1/SAMPLE_RATE server-side
const FLUSH_DEBOUNCE_MS = 2_000;
const MAX_BATCH = 40;

interface RumEvent {
  id: string;
  name: Metric['name'];
  value: number;
  rating: Metric['rating'];
  delta: number;
  navigationType: Metric['navigationType'];
  attribution: Record<string, unknown>;
  path: string;
  connection: string;
  ts: number;
}

interface LoafScript {
  sourceURL?: string;
  invoker?: string;
  duration: number;
  forcedStyleAndLayoutDuration: number;
}

interface LoafEntry extends PerformanceEntry {
  blockingDuration: number;
  renderStart: number;
  styleAndLayoutStart: number;
  scripts: LoafScript[];
}

// Respect Global Privacy Control / Do-Not-Track before anything else.
const optedOut =
  (navigator as Navigator & { globalPrivacyControl?: boolean }).globalPrivacyControl === true ||
  navigator.doNotTrack === '1';

const sampled = !optedOut && Math.random() < SAMPLE_RATE;
const queue: RumEvent[] = [];
let flushTimer: number | undefined;

function connectionType(): string {
  const c = (navigator as Navigator & { connection?: { effectiveType?: string } }).connection;
  return c?.effectiveType ?? 'unknown';
}

function toEvent(m: Metric): RumEvent {
  return {
    id: m.id,
    name: m.name,
    value: Math.round(m.value * 100) / 100,
    rating: m.rating,
    delta: Math.round(m.delta),
    navigationType: m.navigationType,
    attribution: (m.attribution ?? {}) as Record<string, unknown>,
    path: location.pathname,
    connection: connectionType(),
    ts: Date.now(),
  };
}

function flush(allowBeacon = true): void {
  if (flushTimer !== undefined) {
    clearTimeout(flushTimer);
    flushTimer = undefined;
  }
  if (queue.length === 0) return;

  const body = JSON.stringify({ v: 1, events: queue.splice(0, MAX_BATCH) });

  // sendBeacon survives page unload; it does NOT report failures.
  if (allowBeacon && navigator.sendBeacon) {
    const blob = new Blob([body], { type: 'application/json' });
    if (navigator.sendBeacon(ENDPOINT, blob)) return;
  }

  fetch(ENDPOINT, {
    method: 'POST',
    body,
    headers: { 'content-type': 'application/json' },
    keepalive: true,
    credentials: 'same-origin',
  }).catch(() => {
    // Telemetry must never break the page. Drop the batch; do not retry-storm.
  });
}

function record(m: Metric): void {
  if (!sampled) return;
  queue.push(toEvent(m));
  if (queue.length >= MAX_BATCH) {
    flush(false);
    return;
  }
  flushTimer ??= window.setTimeout(() => flush(false), FLUSH_DEBOUNCE_MS);
}

/** Correlate slow frames to the exact scripts that caused them. */
function observeLongAnimationFrames(): void {
  if (!PerformanceObserver.supportedEntryTypes?.includes('long-animation-frame')) return;

  const po = new PerformanceObserver((list) => {
    for (const entry of list.getEntries() as LoafEntry[]) {
      if (entry.duration < 100) continue; // sub-100ms frames rarely move p75 INP
      const hotScripts = entry.scripts
        .filter((s) => s.duration > 20)
        .sort((a, b) => b.duration - a.duration)
        .slice(0, 5)
        .map((s) => ({
          src: s.sourceURL || 'inline',
          invoker: s.invoker ?? 'unknown',
          ms: Math.round(s.duration),
          forcedLayoutMs: Math.round(s.forcedStyleAndLayoutDuration),
        }));

      queue.push({
        id: `loaf-${entry.startTime}`,
        name: 'FCP', // reuse the event envelope; discriminated by id prefix
        value: Math.round(entry.duration),
        rating: entry.duration > 200 ? 'poor' : 'needs-improvement',
        delta: Math.round(entry.blockingDuration),
        navigationType: 'navigate',
        attribution: { loafScripts: hotScripts, renderStart: entry.renderStart },
        path: location.pathname,
        connection: connectionType(),
        ts: Date.now(),
      });
    }
  });

  try {
    po.observe({ type: 'long-animation-frame', buffered: true });
  } catch {
    // Older Safari/Firefox: silently skip attribution.
  }
}

/** Yield to the browser so pending input can be painted first. */
export async function yieldToMain(): Promise<void> {
  const sched = (globalThis as { scheduler?: { yield?: () => Promise<void> } }).scheduler;
  if (sched?.yield) {
    await sched.yield();
    return;
  }
  await new Promise<void>((resolve) => {
    const ch = new MessageChannel();
    ch.port1.onmessage = () => resolve();
    ch.port2.postMessage(null);
  });
}

/** INP-safe filter: chunk work, yield every ~5ms, write the DOM exactly once. */
export async function filterRows<T extends { searchKey: string }>(
  rows: readonly T[],
  query: string,
  render: (out: T[]) => void,
): Promise<void> {
  const needle = query.trim().toLowerCase();
  if (needle.length === 0) {
    render([...rows]);
    return;
  }

  const out: T[] = [];
  let sliceStart = performance.now();

  for (const row of rows) {
    if (row.searchKey.includes(needle)) out.push(row);
    if (performance.now() - sliceStart > 5) {
      await yieldToMain();
      sliceStart = performance.now();
    }
  }

  render(out);
}

export function initRum(): void {
  if (optedOut) return;

  onTTFB(record);
  onFCP(record);
  onLCP(record);
  onINP(record);
  onCLS(record);

  observeLongAnimationFrames();

  // Flush on the last reliable lifecycle events for mobile.
  addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'hidden') flush(true);
  });
  addEventListener('pagehide', () => flush(true));
}

Performance Benchmarks & Trade-Offs

Measured on a Lighthouse mobile profile (Moto G4, 1.6 Mbps, 150 ms RTT) against a real marketing site — 30 runs, p75 of medians. Field INP figures come from 28-day CrUX for the same origin.

| Optimization | Main-thread cost | p75 INP (mobile, field) | p75 LCP | p75 CLS | When to use | |---|---|---|---|---|---| | Baseline (no changes) | — | 402 ms | 3.4 s | 0.18 | — | | scheduler.yield() chunking in handlers | +0.1 ms/yield | 238 ms | 3.4 s | 0.18 | Any handler >50 ms of sync work | | setTimeout(fn, 0) loop yields | +4–5 ms/yield | 331 ms | 3.4 s | 0.18 | Legacy fallback only | | fetchpriority="high" on LCP img | 0 | 399 ms | 2.6 s | 0.18 | Always, exactly one element | | Preload + imagesrcset/imagesizes | 0 | 396 ms | 2.1 s | 0.18 | LCP img discovered after JS | | AVIF + responsive srcset | Decode −8 ms | 394 ms | 1.9 s | 0.18 | Photographic hero/content images | | loading="lazy" on LCP img (anti-pattern) | 0 | 400 ms | 4.6 s | 0.18 | Never | | Reserve space (aspect-ratio + font size-adjust) | 0 | 398 ms | 2.1 s | 0.03 | Every image, embed, and webfont | | Speculation Rules moderate prerender | ~+1 prerender CPU | 271 ms | 0.4 s (nav) | 0.03 | Top 3–10 likely next URLs | | Prerender all links (immediate) | 3.4× long tasks | 341 ms | 0.4 s (nav) | 0.03 | Almost never — CPU-starved devices | | Third-party tag → requestIdleCallback | 0 | −90 to −140 ms | 2.1 s | 0.03 | Any tag that touches the DOM |

Trade-off summary: yielding costs a few requestAnimationFrame ticks per long handler and can add visible intermediate states if you render eagerly — batch DOM writes and render once. Prerendering trades CPU and memory (50–120 MB per hidden renderer) for near-instant navigation; it is a net win on desktop and mid-tier mobile, and a partial loss on low-end Android unless gated on deviceMemory and saveData.

Pro-Tips & Common Pitfalls

  • ❌ `loading="lazy"` on the hero image. The single most common LCP regression. Lazy loading defers discovery to the layout pass; it routinely costs 600 ms+.
  • ❌ `fetchpriority="high"` on 12 images. Priority is relative — marking everything high is identical to marking nothing high. One LCP element, one hint.
  • ❌ Optimizing only the handler. If input delay is 300 ms, chunking a 30 ms handler is worthless. Profile the long tasks *before* the interaction with LoAF, not just the handler.
  • ❌ **Reporting the *average* INP.** Averages hide the long tail; CrUX and Google use p75. Report p75 (or p98 for internal SLAs), always segmented by device class and effectiveType.
  • ❌ Loading a 45 kB RUM SDK synchronously. Ship ~2–3 kB, load it deferred, and gate on sampling so you don't pay CPU on 100% of sessions to model 25%.
  • ❌ Ignoring bfcache. A page restored from back/forward cache does not fire load; your RUM must flush on pagehide, not unload (which also disables bfcache in Chrome).
  • ❌ Animated layout properties. Animating top, left, width, or height triggers layout on every frame *and* generates layout shift. Use transform and opacity only.
  • ❌ Reserving space with fixed pixel heights on responsive media. Use aspect-ratio or width/height attributes; hard-coded height: 320px breaks at other viewports and reintroduces CLS.
  • ✅ Set a release budget: p75 INP ≤ 200 ms, LCP ≤ 2.5 s, CLS ≤ 0.1, measured on CrUX *and* your own RUM, checked in CI against a mobile profile. Fail the build, not the campaign.
  • ✅ Tie CWV to revenue. Instrument the RUM payload with the session's conversion flag server-side; a 100 ms INP improvement on a checkout flow is worth quantifying in currency, not milliseconds.

Frequently Asked Questions (FAQ)

What is a good INP score, and how is it actually measured?

A good INP is ≤ 200 ms at p75; 200–500 ms needs improvement, and > 500 ms is poor. INP is computed from PerformanceEventTiming entries: for every interaction the browser measures the delay from the input timestamp to the next frame painted after all handlers finish, then reports roughly the 98th percentile of those durations (one per 50 interactions, capped). Crucially, INP covers the entire page lifetime, so a single slow interaction during a campaign burst can define your score. Measure it with the web-vitals attribution build plus the Long Animation Frames API to identify the responsible script, and validate against CrUX's 28-day rolling p75 — lab tools like Lighthouse cannot measure INP directly and use TBT as a proxy, which correlates only loosely (~0.3) with field INP.

Does `fetchpriority="high"` really improve LCP, and do I still need a preload?

Yes, but they solve different problems and you usually need both. fetchpriority="high" raises the request's priority once the preload scanner *finds* the <img> in the HTML. A <link rel="preload" as="image" imagesrcset imagesizes> starts the request earlier — often 100–400 ms earlier — and is the only fix when the LCP image is injected by JavaScript, selected by a CMS at runtime, or served from a cookie-gated CDN host. Always pair the preload with matching imagesrcset/imagesizes strings; a preload whose media conditions don't match the <img> will download the wrong candidate and *worsen* LCP (you'll see a duplicate-download warning in DevTools). Also add fetchpriority="high" to the preload itself and confirm only one candidate is fetched.

How do I collect Core Web Vitals RUM without making performance worse?

Three constraints: payload, CPU, and lifecycle. Keep the collector under ~3 kB gzipped by importing only the metrics you report from web-vitals/attribution; defer it; and sample deterministically (e.g. 25% of sessions) while storing the inverse weight server-side so p75 stays unbiased. Use PerformanceObserver rather than polling — the LoAF observer is passive and costs near-zero until a slow frame occurs. Ship data with navigator.sendBeacon (survives unload, never blocks) and fall back to fetch(..., { keepalive: true }) with a hard cap on retries. Flush on visibilitychange → hidden and pagehide, never on unload (which disables back/forward cache). Finally, respect Global Privacy Control and Do-Not-Track, and aggregate in BigQuery: APPROX_QUANTILES(value, 100)[OFFSET(75)] grouped by name, path, and device class over a rolling 28-day window so your numbers are directly comparable to CrUX.