All ArticlesWeb Performance•November 14, 2026•9 min read

Optimizing INP and LCP for Modern SPAs: A Production Playbook for Web Vitals

Single-page applications fail Core Web Vitals for structural reasons — runtime rendering, hydration, and monolithic bundles. This playbook shows you how to instrument, diagnose, and fix Interaction to Next Paint and Largest Contentful Paint with production-grade code and CI guardrails.

Optimizing INP and LCP for Modern SPAs: A Production Playbook for Web VitalsAI Generated with Qwen 3.0 via CometAPI

Modern single-page applications are built on a structural contradiction. The architectural decisions that make an SPA feel instantaneous after the first navigation — client-side routing, a monolithic JavaScript bundle, and runtime rendering — are precisely what inflate Interaction to Next Paint (INP) and Largest Contentful Paint (LCP). Since INP permanently replaced First Input Delay in March 2024, teams can no longer rely on one fast first click to carry a poor score.

This is a practitioner's playbook: how to instrument both metrics with attribution, how to diagnose what is actually blocking the main thread, and how to fix it without rewriting your application.

The SPA Performance Tax: Why Runtime Rendering Costs You Twice

A server-rendered multi-page app ships meaningful HTML on the first byte. The browser can discover the hero image, start the LCP clock's resource load phase early, and paint content before a single line of JavaScript executes.

An SPA ships a nearly empty shell. The browser must:

  1. Download and parse the document skeleton.
  2. Download, parse, compile, and execute the framework runtime and route chunk.
  3. Mount the component tree, which then inserts the hero <img> into the DOM — and only then does the browser discover and fetch it.
  4. Hydrate, attaching every event handler the page needs for INP.

Steps 2–4 are the performance tax. They push LCP's resource load delay and element render delay into the hundreds of milliseconds, and they occupy the main thread at exactly the moment a user is most likely to tap something — which converts directly into input delay for INP.

Field Thresholds You Are Being Measured Against

All Core Web Vitals are evaluated at the 75th percentile of real-user page loads, segmented by mobile and desktop.

MetricGoodNeeds improvementPoor
LCP≤ 2.5 s2.5 – 4.0 s> 4.0 s
INP≤ 200 ms200 – 500 ms> 500 ms
CLS≤ 0.10.1 – 0.25> 0.25

A passing CI Lighthouse score is not evidence of a passing field score. Synthetic runs are single-sample, desktop-weighted, and unthrottled relative to a mid-tier Android device.

INP Anatomy: Input Delay, Processing Time, and Presentation Delay

INP is not the average interaction — it is the 98th percentile of interaction latencies for the page (the worst interaction when fewer than 50 are recorded). One pathological handler is enough to fail the metric.

Every interaction decomposes into three phases:

PhaseWhat it measuresTypical SPA culprit
Input delayTime before your handlers runHydration, third-party tags, competing long tasks
Processing timeHandler + framework workSynchronous state updates, large list re-renders, JSON parsing
Presentation delayStyle, layout, paintDOM size, forced synchronous layout, heavy compositing

The 50 ms Long Task Ceiling

Any task occupying the main thread for more than 50 ms is a long task. During a long task, the browser cannot dispatch an event, run a handler, or paint. If a user taps at 10 ms into a 400 ms task, their input delay alone is 390 ms — the interaction has already failed before a single line of your code runs.

The practical rule: keep every task under 50 ms, and treat 200 ms of blocking work in a single frame as an outage.

Instrumenting INP and LCP With Attribution in Production

You cannot optimize what you cannot attribute. The web-vitals attribution build attaches the diagnostic data you need — which element was the LCP candidate, what caused the slow interaction — to each sample.

ts
// rum/vitals.ts — requires web-vitals v4+ (attribution build)
import { onCLS, onINP, onLCP, type Metric } from 'web-vitals/attribution';

type Attribution = Record<string, string | number | undefined>;

interface VitalSample {
  name: Metric['name'];
  value: number;
  rating: Metric['rating'];
  id: string;
  navigationType: Metric['navigationType'];
  attribution: Attribution;
  route: string;
  ts: number;
}

const ENDPOINT = '/api/rum/vitals';
const MAX_BUFFER = 100;
const buffer: VitalSample[] = [];

function flush(useBeacon = false): void {
  if (buffer.length === 0) return;
  const batch = buffer.splice(0, buffer.length);
  const body = JSON.stringify(batch);

  if (useBeacon && typeof navigator.sendBeacon === 'function') {
    const blob = new Blob([body], { type: 'application/json' });
    if (navigator.sendBeacon(ENDPOINT, blob)) return;
  }

  void fetch(ENDPOINT, {
    method: 'POST',
    body,
    keepalive: true,
    headers: { 'Content-Type': 'application/json' },
  }).catch(() => {
    // Re-queue on failure, but cap growth to protect memory on flaky networks.
    buffer.unshift(...batch.slice(-MAX_BUFFER));
  });
}

// Normalize dynamic segments so routes aggregate correctly:
// /orders/8812/receipt -> /orders/:id/receipt
function currentRoute(): string {
  return location.pathname.replace(/\/\d+\b/g, '/:id');
}

function report(metric: Metric): void {
  buffer.push({
    name: metric.name,
    value: metric.value,
    rating: metric.rating,
    id: metric.id,
    navigationType: metric.navigationType,
    attribution: (metric.attribution ?? {}) as unknown as Attribution,
    route: currentRoute(),
    ts: Date.now(),
  });
  if (buffer.length >= 10) flush();
}

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

addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'hidden') flush(true);
});

Two details matter here. First, sendBeacon on visibilitychange is the only reliable delivery path on mobile Safari, where fetch({ keepalive: true }) can be dropped during page teardown. Second, aggregating by normalized route turns a wall of noisy percentiles into an actionable leaderboard of slow screens.

Diagnosing Long Tasks With the Long Animation Frames API

The Long Animation Frames (LoAF) API supersedes the blunt longtask observer. It attributes blocking time to specific scripts and functions — including third-party code you did not write.

ts
interface LoafSample {
  startTime: number;
  duration: number;
  blockingDuration: number;
  scripts: ReadonlyArray<{ sourceURL: string; sourceFunctionName: string; duration: number }>;
}

export function watchLongAnimations(onSample: (sample: LoafSample) => void): () => void {
  if (!PerformanceObserver.supportedEntryTypes?.includes('long-animation-frame')) {
    return () => {};
  }

  const observer = new PerformanceObserver((list) => {
    for (const entry of list.getEntries() as PerformanceLongAnimationFrameTiming[]) {
      onSample({
        startTime: entry.startTime,
        duration: entry.duration,
        blockingDuration: entry.blockingDuration,
        scripts: entry.scripts.map((s) => ({
          sourceURL: s.sourceURL || '(anonymous)',
          sourceFunctionName: s.sourceFunctionName || '(anonymous)',
          duration: s.duration,
        })),
      });
    }
  });

  observer.observe({ type: 'long-animation-frame', buffered: true });
  return () => observer.disconnect();
}

// Usage: surface the top offender per frame in staging/RUM.
const stop = watchLongAnimations((sample) => {
  if (sample.blockingDuration < 100) return;
  const worst = [...sample.scripts].sort((a, b) => b.duration - a.duration)[0];
  console.warn(
    `[LoAF] ${sample.blockingDuration.toFixed(0)}ms blocking — worst script: ` +
      `${worst?.sourceFunctionName} (${worst?.duration.toFixed(0)}ms) @ ${worst?.sourceURL}`,
  );
});

PerformanceLongAnimationFrameTiming ships in TypeScript's lib.dom from 5.3 onward; on older toolchains, add a local ambient declaration rather than reaching for any.

INP Fix #1: Yield to the Main Thread — Correctly

The single highest-leverage INP change in any SPA is breaking work into yieldable chunks. The modern primitive is scheduler.yield(), which yields to the browser and resumes with priority ahead of queued tasks.

ts
type YieldScheduler = { yield?: () => Promise<void> };

export async function yieldToMain(): Promise<void> {
  const scheduler = (globalThis as { scheduler?: YieldScheduler }).scheduler;

  if (typeof scheduler?.yield === 'function') {
    await scheduler.yield();
    return;
  }

  // Fallback: a macrotask, so pending input and rendering can interleave.
  await new Promise<void>((resolve) => setTimeout(resolve, 0));
}
PrimitiveInterleaves renderingPreserves task prioritySupport
scheduler.yield()YesYes (resumes early)Chromium 129+
setTimeout(fn, 0)YesNo (goes to back of queue)Universal
requestAnimationFrameAfter paint onlyNoUniversal
await Promise.resolve()NoNoUniversal (microtask — do not use)

The common anti-pattern is await Promise.resolve() as a "yield". Microtasks drain before the browser can process input or paint, so the long task is never actually broken.

Chunked Work With an Abort Contract

ts
export interface ChunkOptions {
  signal?: AbortSignal;
  chunkSize?: number;
  budgetMs?: number;
}

export async function processInChunks<T>(
  items: readonly T[],
  handle: (item: T, index: number) => void,
  { signal, chunkSize = 50, budgetMs = 8 }: ChunkOptions = {},
): Promise<{ processed: number; aborted: boolean }> {
  let processed = 0;

  for (let i = 0; i < items.length; i += chunkSize) {
    if (signal?.aborted) return { processed, aborted: true };

    const chunkStart = performance.now();
    const end = Math.min(i + chunkSize, items.length);

    for (let j = i; j < end; j++) {
      handle(items[j] as T, j);
      processed++;
    }

    // Yield only when we actually consumed the frame budget.
    if (performance.now() - chunkStart > budgetMs) {
      await yieldToMain();
    }
  }

  return { processed, aborted: false };
}

INP Fix #2: Keep Handlers Off the Critical Path

Framework-level work is where processing time accumulates. Three patterns deliver most of the win.

Defer Non-Urgent Renders With Transitions

tsx
import { useDeferredValue, useMemo, useState } from 'react';

interface Row { id: string; label: string; amount: number }

export function LedgerSearch({ rows }: { rows: readonly Row[] }): JSX.Element {
  const [query, setQuery] = useState('');
  // Keeps the keystroke paint urgent; the expensive list re-render is deferred.
  const deferredQuery = useDeferredValue(query);

  const results = useMemo(() => {
    const needle = deferredQuery.trim().toLowerCase();
    if (!needle) return rows;
    return rows.filter((r) => r.label.toLowerCase().includes(needle));
  }, [rows, deferredQuery]);

  return (
    <>
      <input
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        placeholder="Search ledger"
        aria-busy={query !== deferredQuery}
      />
      <LedgerList rows={results} />
    </>
  );
}

Use startTransition for route changes and filter transitions; use useDeferredValue when a value drives expensive rendering. Both let React abandon and restart work, which is the difference between a 60 ms and a 400 ms interaction.

Batch DOM Reads and Writes

Interleaving reads (offsetHeight, getBoundingClientRect) with writes (style.x = ..., classList.add) forces synchronous layout — the classic presentation-delay amplifier.

ts
const pendingWrites: Array<() => void> = [];
let frameScheduled = false;

export function scheduleWrite(write: () => void): void {
  pendingWrites.push(write);
  if (frameScheduled) return;
  frameScheduled = true;
  requestAnimationFrame(() => {
    frameScheduled = false;
    // All writes land in one paint, after all reads have completed.
    while (pendingWrites.length > 0) pendingWrites.shift()?.();
  });
}

Shrink the DOM and Stop Re-Rendering the World

  • Virtualize any list above ~100 rows.
  • Apply content-visibility: auto with contain-intrinsic-size to offscreen sections.
  • Memoize row components and pass stable keys — index keys cause full-list reconciliation on reorder.
  • Register scroll and touch listeners as { passive: true } so the compositor never waits on your handler.

LCP Fix #1: Make the Hero Element Discoverable in the Initial HTML

The most common SPA LCP failure is lazy-loading the hero. If the LCP image carries loading="lazy", the browser deprioritizes it until layout settles — guaranteeing a multi-second LCP.

html
<!-- In <head>: start the fetch before the parser reaches the element -->
<link
  rel="preload"
  as="image"
  href="/hero-1600.avif"
  imagesrcset="/hero-800.avif 800w, /hero-1600.avif 1600w"
  imagesizes="100vw"
  fetchpriority="high"
/>

<!-- The element itself: never lazy, always sized, high priority -->
<img
  src="/hero-800.avif"
  srcset="/hero-800.avif 800w, /hero-1600.avif 1600w"
  sizes="100vw"
  width="1600"
  height="900"
  fetchpriority="high"
  decoding="async"
  alt="Quarterly revenue overview"
/>

fetchpriority="high" maps to the u priority parameter defined in RFC 9218, letting you explicitly rank the hero above below-the-fold media without starving the critical CSS.

LCP Fix #2: Attack the Four LCP Subparts

Instrument each phase separately, then fix the largest:

  1. Time to First Byte — Edge-cache the document shell; move personalization to the client. Use 103 Early Hints (RFC 8297) to preload critical assets while the origin renders.
  2. Resource load delay — Eliminate it with server-rendered markup or an explicit <link rel="preload">. Target < 100 ms.
  3. Resource load duration — Serve AVIF/WebP at the actual rendered size via srcset, behind a CDN with Cache-Control: public, max-age=31536000, immutable.
  4. Element render delay — Stop blocking paint on JavaScript. Stream the shell, defer hydration, and avoid render-blocking font CSS.

Tame Hydration and Fonts

  • Adopt selective or progressive hydration (islands, client:visible, React Server Components) so the hero paints before the route chunk executes.
  • Self-host critical fonts, use font-display: swap, and preload only the single weight used above the fold.
  • Audit <head> for render-blocking third parties — a synchronous tag manager is a guaranteed LCP regression on 4G.

Guardrails: CI Budgets and Field Alerts

Synthetic checks catch regressions before they ship; field data confirms the fix. Wire both.

json
{
  "ci": {
    "collect": {
      "url": ["http://localhost:3000/", "http://localhost:3000/pricing"],
      "numberOfRuns": 5,
      "settings": { "preset": "desktop" }
    },
    "assert": {
      "assertions": {
        "categories:performance": ["error", { "minScore": 0.9 }],
        "largest-contentful-paint": ["error", { "maxNumericValue": 2500 }],
        "total-blocking-time": ["error", { "maxNumericValue": 200 }],
        "dom-size": ["warn", { "maxNumericValue": 1400 }],
        "network-requests": ["warn", { "maxNumericValue": 60 }]
      }
    }
  }
}

Total Blocking Time is the best lab proxy for INP — it directly measures main-thread blocking past 50 ms per task. Assert on it in CI and on INP in RUM.

Operational Checklist

  • web-vitals/attribution deployed; samples tagged by normalized route and device class.
  • LoAF observer enabled in staging; the top 5 blocking scripts identified and owned.
  • No task in the critical path exceeds 50 ms; all long loops use processInChunks.
  • scheduler.yield() shipped with a setTimeout fallback; no await Promise.resolve() yields in the codebase.
  • LCP image is server-rendered, preloaded, fetchpriority="high", and never lazy-loaded.
  • Hero LCP < 2.5 s at p75 on throttled mobile, not just localhost.
  • DOM node count under 1,500 for the initial view; lists virtualized above 100 rows.
  • RUM alerting at p75 thresholds with per-route regression detection.

Pitfalls to Avoid

  1. Optimizing the average interaction. INP is a 98th-percentile metric. One slow handler dominates.
  2. Trusting Lighthouse as ground truth. Lighthouse cannot measure INP; it measures TBT. Validate with field data.
  3. Preloading everything. Over-preloading thrashes connection bandwidth and delays the hero. Priority is a zero-sum budget.
  4. Deferring work into `setTimeout` without yielding. Dropping a 300 ms task into six 50 ms tasks in the same frame changes nothing — you must yield between them.
  5. Ignoring third parties. Analytics, chat widgets, and A/B tools routinely own 30–50% of blocking time. Audit them with LoAF, not with a bundle analyzer.
  6. Measuring only the first load. SPA route transitions re-trigger LCP candidates and can introduce heavy synchronous renders; instrument navigation, not just initial pageview.

Sources & Technical References

4 views•0 comments

Discussion (0)

Join the conversation

Loading comments...

Continue Reading

More production-grade engineering deep dives and architectural guides

Explore all articles