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

Taming INP and LCP in Single Page Applications: A Production Playbook

Single Page Applications pay a runtime tax that quietly wrecks Core Web Vitals long after the first paint. This playbook shows how to decompose INP into its three latency budgets, break long tasks with scheduler.yield, and debug LCP sub-parts with real, shippable instrumentation.

Taming INP and LCP in Single Page Applications: A Production PlaybookAI Generated with Qwen 3.0 via CometAPI

Taming INP and LCP in Single Page Applications

Single Page Applications are structurally biased against Core Web Vitals. A multi-page app hands the browser finished HTML and gets out of the way; an SPA ships a JavaScript runtime that must download, parse, evaluate, hydrate, and then re-render on every client-side route change. The result is predictable: LCP is dominated by element render delay because the hero content does not exist until your framework says so, and INP is dominated by input delay because the main thread is still busy reconciling state when the user clicks.

Google retired First Input Delay in March 2024 and replaced it with Interaction to Next Paint, which measures every interaction (clicks, taps, key presses) across the whole page lifecycle and reports a high percentile — roughly the 98th — of the worst observed latencies. That change is brutal for SPAs: a single 600 ms route transition caused by an eagerly-evaluated chunk can now define your score.

This article is the playbook we use in production: how to instrument INP with attribution, how to surgically remove long tasks without rewriting your app, and how to break LCP into four measurable sub-parts so you stop guessing which fix matters.

Why SPAs Fail Core Web Vitals by Design

Three architectural properties cause most of the damage:

  1. Deferred paint. The LCP element (hero image, headline, product card) is often rendered by JavaScript after hydration. TTFB may be excellent while the element is still invisible for 2+ seconds.
  2. Main-thread contention at the worst moment. Hydration, route chunk evaluation, and state reconciliation happen exactly when users begin interacting — the first three seconds.
  3. DOM growth over session lifetime. Long-lived SPAs accumulate nodes. A 15,000-node DOM makes style recalculation and layout measurably slower, which inflates the presentation delay phase of every interaction.

The fix is measurement-driven. You cannot optimize INP without knowing whether you are losing time before the handler runs, inside the handler, or after it returns.

Decomposing INP Into Three Latency Budgets

Every interaction has a deterministic cost structure defined by the Event Timing API:

PhaseWhat it measuresTypical SPA culprit
Input delayTime from user input to the first event callback runningLong tasks from hydration, chunk evaluation, third-party scripts
Processing durationSum of all event handler execution for that interactionHeavy handlers, synchronous filtering, deep reconciliation
Presentation delayTime from handler completion to the next frame paintedForced reflow, huge DOM, expensive CSS (backdrop-filter, box-shadow)

INP is not one problem. It is three, and they require different fixes.

Instrumenting INP with Attribution

The web-vitals library ships an attribution build that surfaces exactly these phases. Use it — do not hand-roll your own observer for the metric itself; only hand-roll for niche diagnostics.

ts
import { onINP, type INPAttribution } from 'web-vitals/attribution';

interface VitalSample {
  id: string;
  value: number;
  rating: 'good' | 'needs-improvement' | 'poor';
  target?: string;
  inputDelay?: number;
  processingDuration?: number;
  presentationDelay?: number;
}

export function trackINP(report: (sample: VitalSample) => void): void {
  onINP(
    (metric) => {
      const attribution = metric.attribution as INPAttribution;
      report({
        id: metric.id,
        value: metric.value,
        rating: metric.rating,
        target: attribution.interactionTarget,
        inputDelay: attribution.inputDelay,
        processingDuration: attribution.processingDuration,
        presentationDelay: attribution.presentationDelay,
      });
    },
    // Report only the final value, but capture interactions from 40ms up
    // so debug builds surface regressions before they hit the 200ms threshold.
    { reportAllChanges: false, durationThreshold: 40 },
  );
}

Read the attribution, not just the number. If inputDelay dominates, you have a long-task problem. If processingDuration dominates, you have a handler problem. If presentationDelay dominates, you have a rendering problem — go look at DOM size and forced synchronous layout.

Killing Long Tasks With a Yield-First Architecture

The browser treats any task over 50 ms as a long task. During a long task, input events queue up: that queueing time is literally your input delay. The remedy is to slice work into sub-50 ms chunks and voluntarily yield so the event loop can dispatch pending input.

A Drop-in yieldToMain and Time Slicer

Chromium 129+ ships scheduler.yield(), which yields and resumes at elevated priority at the front of the queue — unlike setTimeout(0), which gets starved behind rendering and other tasks.

ts
type Yield = () => Promise<void>;

const schedulerApi = (globalThis as { scheduler?: { yield?: () => Promise<void> } }).scheduler;

export const yieldToMain: Yield =
  typeof schedulerApi?.yield === 'function'
    ? () => schedulerApi.yield!()
    : typeof globalThis.requestIdleCallback === 'function'
      ? () =>
          new Promise<void>((resolve) => {
            globalThis.requestIdleCallback(() => resolve(), { timeout: 100 });
          })
      : () => new Promise<void>((resolve) => setTimeout(resolve, 0));

export async function timeSlice<T>(
  items: readonly T[],
  work: (item: T, index: number) => void,
  budgetMs = 8,
): Promise<void> {
  let sliceStart = performance.now();
  for (let i = 0; i < items.length; i++) {
    work(items[i]!, i);
    if (performance.now() - sliceStart >= budgetMs) {
      await yieldToMain();
      sliceStart = performance.now();
    }
  }
}

Wrap any work loop over ~50 iterations — hydrating a deferred section, precomputing search indexes, normalizing a large API payload — in timeSlice. An 8 ms budget keeps you far from the 50 ms long-task boundary and leaves headroom for the browser's own rendering work.

Catching Regressions With the Long Animation Frames API

LoAF attributes a slow frame to specific script URLs and even specific invoker types (e.g. IMG.onload, Promise.then, user callback). It is the fastest way to find the third-party script destroying your input delay.

ts
type LoAFScript = {
  invoker?: string;
  sourceURL?: string;
  sourceFunctionName?: string;
  duration: number;
  forcedStyleAndLayoutDuration: number;
};

type LoAFEntry = PerformanceEntry & { blockingDuration: number; scripts: LoAFScript[] };

export function watchLongAnimationFrames(slowMs = 100): void {
  if (typeof PerformanceObserver === 'undefined') return;
  if (!PerformanceObserver.supportedEntryTypes?.includes('long-animation-frame')) return;

  const observer = new PerformanceObserver((list) => {
    for (const raw of list.getEntries()) {
      const entry = raw as LoAFEntry;
      if (entry.duration < slowMs) continue;

      const culprits = [...entry.scripts]
        .sort((a, b) => b.duration - a.duration)
        .slice(0, 3)
        .map(
          (s) =>
            `${s.sourceFunctionName ?? s.invoker ?? 'anonymous'} @ ${s.sourceURL ?? 'inline'} ` +
            `(${Math.round(s.duration)}ms, style/layout ${Math.round(s.forcedStyleAndLayoutDuration)}ms)`,
        );

      console.warn(
        `[LoAF] ${Math.round(entry.duration)}ms frame, blocked ${Math.round(entry.blockingDuration)}ms`,
        culprits,
      );
    }
  });

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

blockingDuration is the number that maps most directly to INP pain: it is the total time the frame was unresponsive to input. Ship this only in your debug/QA build, or sample it heavily in production.

Hydration and Route Transitions: The Two INP Killers

Most SPA INP regressions trace to two moments: initial hydration, and the first interaction after a route change.

Hydration. Hydrate incrementally — islands or selective hydration — and never hydrate below-the-fold trees eagerly. If your framework supports it, gate hydration of below-fold sections behind requestIdleCallback or an intersection observer.

Chunk evaluation. A route chunk that is fetched on click but evaluated immediately will block the main thread for hundreds of milliseconds. Prefetch chunks during idle and warm them proactively via Speculation Rules:

json
{
  "prefetch": [
    { "where": { "href_matches": "/product/*" }, "eagerness": "moderate" }
  ],
  "prerender": [
    { "where": { "href_matches": "/checkout" }, "eagerness": "conservative" }
  ]
}

Handler work. Offload non-urgent state updates from the interaction path. In React 18+, useDeferredValue and startTransition let the browser paint the next frame before the expensive render completes:

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

type Product = { id: string; name: string };

export function ProductSearch({ products }: { products: Product[] }) {
  const [query, setQuery] = useState('');
  const deferredQuery = useDeferredValue(query);

  const results = useMemo(
    () => products.filter((p) => p.name.toLowerCase().includes(deferredQuery.toLowerCase())),
    [products, deferredQuery],
  );

  return (
    <>
      <input value={query} onChange={(e) => setQuery(e.target.value)} aria-label="Search products" />
      <ul data-stale={query !== deferredQuery}>
        {results.map((p) => (
          <li key={p.id}>{p.name}</li>
        ))}
      </ul>
    </>
  );
}

Optimizing LCP in a Client-Routed App

LCP is the render time of the largest image or text block in the viewport, and it stops being updated after the first user interaction. Break it into its four official sub-parts before touching anything.

Measuring the Four LCP Sub-Parts

The Largest Contentful Paint spec defines: TTFB, resource load delay, resource load duration, and element render delay. Subtracting activationStart handles prerendered pages correctly.

ts
interface LCPBreakdown {
  ttfb: number;
  resourceLoadDelay: number;
  resourceLoadDuration: number;
  elementRenderDelay: number;
  total: number;
}

export function observeLCPBreakdown(onReport: (b: LCPBreakdown) => void): void {
  const nav = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming | undefined;
  const activationStart = (nav as unknown as { activationStart?: number } | undefined)?.activationStart ?? 0;

  new PerformanceObserver((list) => {
    const entries = list.getEntries();
    const lcp = entries[entries.length - 1] as
      | (PerformanceEntry & { renderTime: number; loadTime: number; url?: string })
      | undefined;
    if (!lcp) return;

    const renderTime = lcp.renderTime || lcp.loadTime || lcp.startTime;
    const resource = lcp.url
      ? (performance.getEntriesByName(lcp.url, 'resource')[0] as PerformanceResourceTiming | undefined)
      : undefined;

    const ttfb = Math.max(0, (nav?.responseStart ?? 0) - activationStart);
    const resourceLoadDelay = resource ? Math.max(0, resource.startTime - ttfb) : 0;
    const resourceLoadDuration = resource ? Math.max(0, resource.responseEnd - resource.startTime) : 0;
    const elementRenderDelay = Math.max(
      0,
      renderTime - activationStart - ttfb - resourceLoadDelay - resourceLoadDuration,
    );

    onReport({ ttfb, resourceLoadDelay, resourceLoadDuration, elementRenderDelay, total: renderTime - activationStart });
  }).observe({ type: 'largest-contentful-paint', buffered: true });
}

In SPAs, elementRenderDelay routinely exceeds 60% of total LCP. That tells you the problem is when you render, not how fast the bytes arrive — and no amount of CDN tuning will fix it.

Preloading the Real Hero Asset

Never let the LCP image be discovered by the preload scanner as a low-priority <img>. Declare it explicitly with Priority Hints and a responsive imagesrcset:

html
<link
  rel="preload"
  as="image"
  href="/hero-800.avif"
  imagesrcset="/hero-800.avif 800w, /hero-1600.avif 1600w"
  imagesizes="100vw"
  fetchpriority="high"
/>
<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="Product dashboard preview"
/>

Pair this with 103 Early Hints for third-party origins and rel="preconnect" only for origins genuinely on the critical path — excess preconnects compete for sockets.

Shipping Real User Monitoring That Survives Sampling

Lab data lies about INP: it cannot simulate real interaction distributions. Emit RUM events with sendBeacon so they survive unload, and sample aggressively — you need percentiles, not every event.

ts
type RUMEvent = {
  metric: 'INP' | 'LCP' | 'CLS';
  value: number;
  rating: string;
  id: string;
  path: string;
  fields?: Record<string, number | string | undefined>;
};

const ENDPOINT = '/api/rum';
const SAMPLE_RATE = 0.1; // 10% of sessions

export function reportVital(event: RUMEvent): void {
  if (Math.random() > SAMPLE_RATE) return;

  const body = new Blob([JSON.stringify({ ...event, ts: Date.now() })], { type: 'application/json' });
  if (navigator.sendBeacon?.(ENDPOINT, body)) return;

  void fetch(ENDPOINT, {
    method: 'POST',
    body,
    keepalive: true,
    headers: { 'content-type': 'application/json' },
  }).catch(() => {
    // Telemetry must never break the page.
  });
}

Slice every dashboard by path, device class, and connection type. Averages hide the p75 mobile user who is your actual Core Web Vitals problem.

Operational Checklist

  • ✅ Alert on p75 INP > 200 ms and p75 LCP > 2.5 s per route, not site-wide.
  • ✅ Track inputDelay / processingDuration / presentationDelay ratios as separate time series.
  • ✅ Budget route chunks: fail CI if any route chunk exceeds ~150 KB gzipped.
  • ✅ Run watchLongAnimationFrames() in QA; file a ticket for every frame over 200 ms.
  • ✅ Cap DOM nodes per view (~1,500 rendered); virtualize any list over 50 items.
  • ✅ Audit third-party scripts quarterly — they are the most common LoAF culprit.
  • ✅ Verify LCP preload in the rendered HTML for every template, including client-routed ones.

Pitfalls That Quietly Destroy INP

  • `setTimeout(0)` instead of `scheduler.yield()`. Timer callbacks are deprioritized and can be delayed hundreds of milliseconds behind rendering.
  • Measuring INP in a warm lab session. Your first interaction after hydration is 3–5× slower than steady state; synthetic runs miss it.
  • Allocating in scroll/pointer handlers. pointermove handlers that allocate objects trigger GC pauses that surface as presentation delay.
  • `will-change` on everything. Over-promoting layers increases memory and compositing cost; use it only on elements that actually animate.
  • Ignoring `forcedStyleAndLayoutDuration`. Reading offsetHeight inside a loop forces synchronous layout on every iteration — the classic 4× slowdown.
  • Optimizing TTFB when `elementRenderDelay` dominates. Check the sub-parts before you touch infrastructure.

Sources & Technical References

2 views•0 comments

Discussion (0)

Join the conversation

Loading comments...

Continue Reading

More production-grade engineering deep dives and architectural guides

Explore all articles