---
type: Concept
resource: https://web.dev/articles/vitals
generated: { by: reference_agent/antigravity, at: 2026-11-15T02:33:00Z }
tags:
  - web
  - performance
  - core-web-vitals
  - lcp
  - cls
  - react
  - vite
sources:
  - resource: https://web.dev/articles/optimize-cls
    title: "Optimize Cumulative Layout Shift (web.dev)"
  - resource: https://web.dev/articles/optimize-lcp
    title: "Optimize Largest Contentful Paint (web.dev)"
  - resource: https://developer.mozilla.org/en-US/docs/Web/CSS/font-size-adjust
    title: "CSS font-size-adjust (MDN)"
---

# Core Web Vitals Optimization for Vite and React SPAs

Optimizing **Largest Contentful Paint (LCP)** and **Cumulative Layout Shift (CLS)** in client-rendered React and Vite Single-Page Applications (SPAs) backed by static HTML skeletons requires keeping entry bundles free of bulk documentation payloads, locking navigation bar geometry across asynchronous auth/data fetches, aligning pre-hydration skeleton CSS with hydrated components, and preloading primary web fonts early.

## Splitting Route Metadata from Content Payloads

A common mobile LCP bottleneck in SPAs occurs when routing or redirect configuration imports a large generated content map (such as pre-rendered HTML and raw Markdown across multiple locales) directly into the application shell (`App.tsx` or `routes.ts`). Even when page components are code-split via `React.lazy`, importing the shared data module pulls the entire payload into the entry chunk (`main-*.js`), delaying parsing, execution, and hydration on mobile CPUs.

- **Extract Lightweight Metadata**: Emit a separate tiny metadata module (`docs-meta.generated.ts` containing only `firstSlug` and `slugs[]` per locale) during docs generation alongside the heavy content payload (`docs-data.generated.ts`). Import only the metadata module in routing tables, sitemap helpers, and landing redirects so lazy docs routes own the heavy chunk.
- **Lazy-Load Non-Critical Header Modals**: Keep modal dialogs triggered by navbar buttons behind `React.lazy(...)` and `<Suspense fallback={null}>`, rendering them conditionally only when opened.

In a Vite + React application with 4 locales of documentation, decoupling route metadata and lazy-loading header modals reduced the entry bundle from ~1.25 MB to ~343 KB (`~107 KB` gzipped) and lowered mobile Lighthouse LCP from `5.7 s` (`Score: 0.16`) to `0.8 s` (`Score: 1.0`).

## Locking Navigation Bar Height Across Async State

Real-User Monitoring (RUM) often reports vertical CLS on `<main>` (`min-h-[calc(100vh-...)]`) when an unfixed `<nav>` above it changes height by even a few pixels as client authentication or user-balance fetches settle asynchronously.

- **Fix Row and Container Heights**: Apply explicit `min-height` / `height` constraints (e.g., `min-h-7 md:h-9` on the nav inner wrapper and `h-9` on action button groups) instead of letting padding and font-size changes expand the header bar mid-load.
- **Render Locale Controls Unconditionally**: Mount locale switchers outside async auth gates (`<Show>`) so controls do not pop in or jump horizontally/vertically after auth initialization.
- **Reserve Auth-Loading Slots**: Check auth readiness (`useAuth().isLoaded`) and render an identically sized placeholder while authentication state is pending, preventing signed-in/signed-out swap jumps.
- **Match Skeleton and Loaded Control Geometry**: Ensure async badges (such as a credit meter loading placeholder vs rendered button) share identical height (`h-8`) and icon links use fixed-square boxes (`h-9 w-9`) rather than oversized emoji padding.

## Aligning Pre-Hydration Skeletons with Hydrated Views

When serving an immediate static HTML shell inside `index.html` to accelerate FCP/LCP before React mounts, even small CSS discrepancies between `.skeleton-*` rules and the live Tailwind component classes produce layout shifts upon hydration:

- **Match Breakpoints and Type Metrics**: Keep mobile/tablet padding, `min-height`, heading/subtitle font sizes, badge line heights, code-preview heights, and stacked mobile CTA flex directions identical between the shell CSS and the hydrated component.
- **Clear Route-Mismatched Hero Skeletons**: If a build step pre-renders multiple public routes from `index.html`, replace landing-page hero markup inside `<main class="skeleton-main">` with an empty container on non-landing routes (e.g., pricing or agent catalog pages) so non-landing visitors never flash and replace landing hero geometry.

## Preloading Primary Web Fonts and Stabilizing Fallbacks

Inlining full CSS bundles into production HTML guarantees fast FCP, yet discovering `@font-face` rules near the bottom of an inlined `<style>` block delays font downloads until CSS tokenization finishes.

- **Inject Font Preload Tags Before Inlined CSS**: Emit `<link rel="preload" as="font" type="font/woff2" href="/assets/<primary-font>.woff2" crossorigin />` ahead of the inlined `<style>` block so the browser initiates the WOFF2 request alongside initial document parsing. Because Vite's dev server resolves CSS and `@fontsource` assets dynamically via ESM without production preloads, Playwright dev-mode runs can still observe minor mobile wrap shifts while built `dist/` artifacts audited by Lighthouse achieve `CLS: 0`.
- **Match Fallback Proportions**: Add `font-size-adjust: from-font` on `body` to align fallback glyph x-heights with the web font and reduce text reflow on swap.

## Testing Strategy

Combining two complementary checks prevents regressions across both dev iteration and production artifacts:

- **Vitest Data-Lockstep Unit Test**: Assert that lightweight route metadata (`DOCS_META_BY_LOCALE`) matches `Object.keys(DOCS_DATA_BY_LOCALE[locale].pages)` and every normalized route appears in `getAllRoutes()`.
- **Playwright Layout-Stability Test + Production Lighthouse Audit**: Inject a `PerformanceObserver` for `layout-shift` entries (`!hadRecentInput`), verify `<nav>` height and `<main>` `y`-coordinate invariance across delayed `/v1/accounts/me` responses (with list endpoints like `/v1/ai/agents` mocked cleanly so error alerts do not mask header measurements), and validate final production bundles via Lighthouse (`[[https://web.dev/articles/vitals]]`).
