The first time I got paged at 2am because Core Web Vitals dropped on a customer-facing marketing site, I was annoyed. CWV isn't a real incident, I thought. Then I checked the dashboards: a 200ms regression in LCP had produced a 7% drop in conversion over 48 hours, which is real money, and suddenly CWV felt like a real incident. Google's not subtle about this-page experience is a ranking signal, and users bounce off slow pages. Performance is product.
The good news is that CWV is one of the rare performance areas where the metric, the tooling, and the fixes are all well-defined. The bad news is that "well-defined" doesn't mean "easy." Moving LCP from 3.5s to 2.0s usually requires touching image strategy, server response time, and your critical CSS path simultaneously. This article is the playbook I use when I get called in to fix a slow site.
What Core Web Vitals Actually Measures
Three metrics, as of the March 2024 update:
| Metric | Measures | Good | Needs improvement | Poor |
|---|---|---|---|---|
| LCP (Largest Contentful Paint) | Loading: time until the largest visible element renders | ≤ 2.5s | 2.5-4.0s | > 4.0s |
| INP (Interaction to Next Paint) | Responsiveness: max interaction latency over page lifetime | ≤ 200ms | 200-500ms | > 500ms |
| CLS (Cumulative Layout Shift) | Visual stability: total unexpected layout shift | ≤ 0.1 | 0.1-0.25 | > 0.25 |
INP replaced FID (First Input Delay) in March 2024. FID only measured the delay of the first interaction; INP measures the worst interaction across the whole session. It's a much harsher metric-a page that feels snappy on load but janky on a SPA route transition will pass FID and fail INP.
Google also tracks a longer list of "lab" and "field" metrics: TTFB, FCP, TBT, TTI. CWV is the headline trio; the others are diagnostic.
Lab vs field matters. Lab data (Lighthouse running in CI) is synthetic-it's your site on a simulated Moto G4 over slow 4G. Field data (Chrome UX Report / CrUX, Real User Monitoring) is what real users actually experience. Google ranks on field data. You optimize with lab data because you can iterate fast. The two often disagree-your lab LCP is 1.8s, your field LCP is 3.2s because real users are on slow phones in countries you forgot to test from. Always check both.
Why Developers Care
Three reasons:
- SEO. Page experience is a Google ranking signal. Not the biggest signal-content relevance dominates-but in competitive niches, CWV is the tiebreaker. Two equally-relevant pages, the faster one wins.
- Conversion. Multiple public studies (Deloitte, Google, Akamai) have shown 100-300ms improvements in load time produce measurable conversion lifts. Pinning exact numbers is dangerous because every site is different, but the direction is unambiguous: faster = more revenue.
- User experience is product. A janky page that shifts layout as it loads feels broken. Users don't articulate it as "CLS is 0.18," they articulate it as "this site is annoying" and they don't come back.
Architecture: Where CWV Regressions Come From
A typical web app and the usual suspects for each metric:
CodeCopy
+-----------------+ +------------------+ +------------------+
| Network | | Server | | Browser |
|-----------------| |------------------| |------------------|
| DNS, TCP, TLS | | TTFB | | Parse HTML |
| RTT to origin |--->| Server render |--->| Fetch critical |
| CDN hit/miss | | (SSR/CSR/SSG) | | resources |
| | | DB queries | | Execute JS |
+-----------------+ +------------------+ | Layout / paint |
| Hydration |
| User interaction |
+------------------+
|
v
+----------------------------+
| LCP drivers: |
| - TTFB |
| - Image load time |
| - Render-blocking JS/CSS |
| - Font swap |
| |
| INP drivers: |
| - Long tasks on main |
| - Heavy hydration |
| - Third-party scripts |
| - Unoptimized event |
| handlers |
| |
| CLS drivers: |
| - Images without dims |
| - Web fonts (FOUT/FOIT) |
| - Late-loading embeds |
| - Async ads |
+----------------------------+
The single biggest source of CWV regressions in modern apps is JavaScript. Every KB of JS you ship has to be downloaded, parsed, compiled, and executed, all of which blocks the main thread and starves LCP, INP, and CLS simultaneously. The second biggest is images-LCP is almost always an image on content-heavy pages, and unoptimized images are the most common cause of slow LCP.
Prerequisites and Measurement Setup
You can't optimize what you can't measure. Three layers:
1. Lab (synthetic, in CI): Lighthouse.
2. Local dev: Lighthouse in Chrome DevTools, plus the web-vitals Chrome extension.
3. Field (real users): web-vitals JS library beacons to your RUM endpoint. Also check Google Search Console (CrUX data, free) and PageSpeed Insights (which surfaces CrUX).
Install the web-vitals library:
BashCopy
shell
npm install web-vitals@4.2.4
plaintext
src/vitals.js:
JavaScriptCopy
javascript
import { onLCP, onINP, onCLS, onFCP, onTTFB } from 'web-vitals';
function sendToAnalytics(metric) {
// Don't send in dev unless explicitly enabled
if (import.meta.env.DEV && !import.meta.env.VITE_SEND_VITALS) return;
const body = JSON.stringify({
name: metric.name,
value: metric.value,
rating: metric.rating, // 'good' | 'needs-improvement' | 'poor'
id: metric.id,
delta: metric.delta,
navigationType: metric.navigationType,
path: window.location.pathname,
// Optional: A/B test variant, user segment, etc.
sessionId: window.SESSION_ID,
});
// Use sendBeacon to avoid blocking on unload
if (navigator.sendBeacon) {
navigator.sendBeacon('/api/vitals', body);
} else {
fetch('/api/vitals', { body, method: 'POST', keepalive: true });
}
}
export function initVitals() {
onLCP(sendToAnalytics);
onINP(sendToAnalytics);
onCLS(sendToAnalytics);
onFCP(sendToAnalytics);
onTTFB(sendToAnalytics);
}
plaintext
Call from main.js:
JavaScriptCopy
javascript
import { initVitals } from './vitals';
initVitals();
plaintext
A minimal backend collector (Node/Express):
JavaScriptCopy
javascript
app.post('/api/vitals', express.json(), (req, res) => {
const { name, value, rating, path, sessionId } = req.body;
// In production: batch into BigQuery, ClickHouse, or Datadog
console.log(JSON.stringify({ name, value, rating, path, sessionId, ts: Date.now() }));
res.status(204).end();
});
plaintext
Use sendBeacon or fetch(..., { keepalive: true }) because regular fetches get cancelled on page unload, and CLS especially is reported late.
Lighthouse CI config (.lighthouserc.json):
JSONCopy
json
{
"ci": {
"collect": {
"url": ["http://localhost:3000/", "http://localhost:3000/products/widget"],
"numberOfRuns": 3,
"settings": { "preset": "desktop", "throttling": { "rttMs": 40, "throughputKbps": 10240 } }
},
"assert": {
"assertions": {
"largest-contentful-paint": ["error", { "maxNumericValue": 2500 }],
"interactive": ["warn", { "maxNumericValue": 200 }],
"cumulative-layout-shift": ["error", { "maxNumericValue": 0.1 }],
"uses-responsive-images": "warn"
}
},
"upload": { "target": "temporary-public-storage" }
}
}
markdown
Wire this into CI. Fail the build on LCP > 2.5s or CLS > 0.1. Warn on INP > 200ms. Don't fail on INP in lab-it's a noisy metric in synthetic tests and INP is fundamentally a field metric.
LCP Optimization: The Big Lever
LCP is almost always an image, a video poster, a large heading with a web font, or a hero block. The strategies, in order of impact:
1. Reduce TTFB. LCP can't start before the first byte arrives. If your TTFB is 800ms, your LCP floor is 800ms plus whatever it takes to render the hero. Target TTFB < 600ms at p75. Levers: CDN edge caching, SSR over CSR, faster database queries, fewer waterfall API calls during render.
2. Preload the LCP image. If your hero image is referenced in CSS or lazy-loaded by JS, the browser doesn't start fetching it until late. Tell the browser up front:
HTMLCopy
html
fetchpriority="high" imagesrcset="/hero-480.webp 480w, /hero-1024.webp 1024w, /hero-1920.webp 1920w"
imagesizes="100vw" />
plaintext
fetchpriority="high" is the modern way to hint priority (Chrome 101+, Safari 17+, Firefox 140+). It's more reliable than the old rel=preload trick alone.
3. Serve modern image formats. AVIF and WebP are 30-50% smaller than JPEG at equivalent quality. Use <picture> with fallbacks:
HTMLCopy
html
width="1024" height="576" alt="Hero" fetchpriority="high" decoding="async" />
markdown
4. Set explicit width/height. Without dimensions, the browser can't reserve space, layout is delayed, and CLS gets worse too.
5. Don't lazy-load the LCP image. This is a common mistake. loading="lazy" on the hero image delays it. Lazy-load images below the fold, not above it.
6. Inline critical CSS, defer the rest. Render-blocking CSS in <head> blocks first paint. Inline the CSS needed for above-the-fold render (typically 10-30KB), and load the rest asynchronously:
HTMLCopy
html
markdown
Tools like Critters (Vite plugin) automate this.
7. Self-host fonts or use font-display: swap. Google Fonts adds a DNS lookup, connection, and request to a third-party origin. Self-hosting saves ~200ms. If you must use Google Fonts, at minimum set font-display: swap so text renders immediately with a fallback:
CSSCopy
css
@font-face {
font-family: 'Inter';
src: url('/fonts/inter-var.woff2') format('woff2');
font-display: swap;
font-weight: 100 900;
}
markdown
8. SSR or SSG the page shell. Client-side rendering means the browser gets an empty HTML page, downloads JS, executes JS, then fetches data. LCP is hopeless in that model. Use SSR (Next.js, Remix, SvelteKit) or SSG for content pages. CSR is fine for app-like experiences behind auth, where LCP isn't a ranking concern.
INP Optimization: The New Hard Metric
INP measures the worst interaction latency in the page's lifetime. Tap a button, how long until the screen updates? That's the interaction latency. INP is the worst (or near-worst) of those, sampled across the session.
INP replaced FID in March 2024. FID only measured the input delay (the gap between tap and event handler start). INP measures the full interaction: input delay + processing time + presentation delay. A handler that starts quickly but takes 300ms to run fails INP even though it would have passed FID.
The dominant cause of poor INP is main-thread blocking. JavaScript is single-threaded. If a 250ms task is running when the user taps, the tap waits.
1. Break up long tasks. Anything over 50ms is "long" by Chrome's definition. Use scheduler.yield() (Chrome 129+) or setTimeout to break work into chunks:
JavaScriptCopy
javascript
// Old: one long task
function processAll(items) {
items.forEach(item => expensiveWork(item));
}
// New: yield between chunks
async function processAllYielding(items) {
const CHUNK = 20;
for (let i = 0; i < items.length; i += CHUNK) {
const chunk = items.slice(i, i + CHUNK);
chunk.forEach(item => expensiveWork(item));
// Yield to the browser so it can handle input
if ('scheduler' in window && 'yield' in scheduler) {
await scheduler.yield();
} else {
await new Promise(r => setTimeout(r, 0));
}
}
}
markdown
2. Defer non-critical JS. Use defer on all non-critical scripts (which means basically all of them). defer blocks execution until after HTML parse, doesn't block rendering:
HTMLCopy
html
plaintext
Avoid async for app-critical scripts-async executes whenever downloaded, which can be mid-render.
3. Lazy-load below-the-fold components. If your homepage has 8 sections and only the first 2 are visible initially, code-split the rest:
JavaScriptCopy
jsx
const HeavyChart = lazy(() => import('./HeavyChart'));
function Page() {
return (
<>
}>
</>
);
}
markdown
4. Use requestIdleCallback for non-urgent work. Analytics, prefetching, telemetry-anything that doesn't need to happen now:
JavaScriptCopy
javascript
function sendAnalytics(event) {
if ('requestIdleCallback' in window) {
requestIdleCallback(() => navigator.sendBeacon('/api/event', JSON.stringify(event)));
} else {
navigator.sendBeacon('/api/event', JSON.stringify(event));
}
}
markdown
5. Trim third-party scripts. Analytics, chat widgets, A/B testing, ads-each one is 50-300KB of JS that runs on your main thread. Audit them quarterly. Use Partytown or a web worker to move them off the main thread:
HTMLCopy
html
markdown
6. Hydration is expensive. React hydration walks the entire DOM tree and attaches listeners. On large pages this can be 500ms+ of main thread blocking. Solutions: React 18 progressive hydration, Astro's islands architecture, or just render less stuff server-side and hydrate only interactive bits.
CLS Optimization: Visual Stability
CLS measures unexpected layout shifts. Each shift is scored by impact (area moved) × distance fraction. Sum them up over the page lifetime, cap at 1.0 per session for older versions, though the current spec caps per-shift contributions to avoid one bad shift dominating.
Common causes and fixes:
1. Images and embeds without dimensions. Always specify width and height (or aspect-ratio in CSS):
HTMLCopy
markdown
Without dimensions, the browser doesn't know how much space to reserve. When the image loads, content below it shifts. This is the #1 cause of CLS on the web.
2. Web fonts. When a font loads and replaces the fallback, the new font's metrics differ, and text reflows. Three fixes:
-
font-display: swap(renders fallback first, swaps when ready)-trades CLS for FOUT (flash of unstyled text). -
size-adjustand font metric overrides in@font-faceto make the fallback match the web font's metrics:
CSSCopy
css
@font-face {
font-family: 'Inter Fallback';
src: local('Arial');
size-adjust: 100.5%;
ascent-override: 90%;
descent-override: 22%;
line-gap-override: 0%;
}
plaintext
- Self-host and preload the font file so it loads before first paint. Eliminates the swap entirely.
3. Dynamically injected content. Banners, cookie consent, ads pushed into the top of the page shift everything below. Reserve space with min-height:
CSSCopy
css
.cookie-banner-slot { min-height: 60px; }
.ad-slot { min-height: 250px; }
markdown
Or use the new loading="lazy" on iframes combined with reserved space.
4. Async web components. A React component that fetches data and renders a list shifts everything below when it loads. Reserve space with skeletons:
JavaScript (JSX)Copy
jsx
function ProductList() {
const { data, loading } = useFetch('/api/products');
if (loading) return ;
return data.map(p => );
}
markdown
The skeleton has the same height as the loaded list, so no shift.
5. CSS transforms, not top/left. Animations using top, left, margin cause layout. Use transform: translate(...) which doesn't trigger layout. The browser can animate transforms on the compositor thread.
Production Considerations
RUM over synthetic. Lab data is for iterating. Field data is what users experience. Once you ship, watch the field data. Use CrUX dashboard, Search Console, or your own RUM endpoint. Look at p75, not averages-Google ranks on p75.
A/B test performance changes. "We improved LCP by 400ms" without measuring conversion impact is a story, not a result. Run changes as A/B tests when you can.
Third-party governance. Marketing adds a tag manager, then a chat widget, then a heat map, then a session recorder. Each one costs 50-200ms of INP. Establish a process: every new third-party script needs perf budget sign-off.
Set a perf budget. Concrete numbers in CI:
JSONCopy
json
{
"resourceSizes": [
{ "resourceType": "script", "budget": 200 },
{ "resourceType": "stylesheet", "budget": 30 },
{ "resourceType": "image", "budget": 500 },
{ "resourceType": "total", "budget": 1000 }
],
"resourceCounts": [
{ "resourceType": "third-party", "budget": 10 }
]
}
markdown
Lighthouse CI can enforce these.
Monitor by route. Aggregate metrics per route. Your homepage might be fast; your /products/[id] page might be slow because of an unoptimized image pipeline. Route-level dashboards reveal this.
Mobile vs desktop separately. Mobile is usually 2-3x slower than desktop on the same codebase. Track them separately and prioritize mobile.
Alerting. Set alerts on p75 LCP, INP, CLS regressions of more than 10% week-over-week. Don't alert on every blip-CWV is noisy.
Common Mistakes
Optimizing for Lighthouse, not users. A 100 Lighthouse score with a 4s field LCP because real users are on 3G in Brazil. Lab is a proxy, not the goal. The goal is field performance.
Lazy-loading the LCP image. Saves bytes, kills LCP. Above-the-fold images should be eagerly loaded with fetchpriority="high".
Over-relying on defer. defer helps, but a 800KB deferred bundle still blocks the main thread for parsing/compilation. The real fix is shipping less JS.
Ignoring web font CLS. "Just set font-display: swap" is the common advice, but swap still causes a visible reflow. Use font metric overrides or self-host with preload.
Adding Partytown without measuring. Partytown helps for heavy third-party scripts, but it has overhead. Measure before and after. For one light analytics script, it's not worth it.
Chasing CWV in dev mode. Vite dev mode is unminified, unsplit, with HMR overhead. Measure with vite build && vite preview or a staging deploy. Dev mode numbers are meaningless.
Forgetting INP on SPA route transitions. INP measures the whole session, including client-side navigation. A heavy route transition handler tanks INP even if initial load is fast.
Troubleshooting Real-World CWV Regressions
Symptom: LCP jumped from 2.0s to 4.5s overnight on mobile.
Cause: Marketing added a 3MB hero video, lazy-loaded, that competed with the LCP image for bandwidth. Fix: remove the video on mobile, or set preload="none" and don't autoplay on mobile networks.
Symptom: INP at 450ms on a single product page, 180ms everywhere else.
Cause: That page had a 2MB React bundle for a configurator widget that hydrated on load. Fix: code-split the configurator, hydrate only when user scrolls to it.
Symptom: CLS at 0.18 only on mobile.
Cause: Mobile layout used a sticky header that grew by 40px when a cookie banner appeared, shifting all content. Fix: reserve space for the banner with min-height on a wrapper, or render the banner inline at the bottom.
Symptom: Lab LCP is 1.8s, field LCP is 3.5s.
Cause: Lab runs from a server in the same region as the test machine. Field users are 200ms RTT away. Fix: CDN edge caching for HTML, prefetch critical resources on previous-page hover.
Symptom: INP spikes every Monday at 9am.
Cause: A scheduled report runs heavy JS on the dashboard page during Monday morning active hours. Fix: move the report computation server-side, paginate the data.
Symptom: Performance is great in Chrome, terrible in Safari.
Cause: Safari doesn't support scheduler.yield(), doesn't have the same task scheduling, and JavaScriptCore parses large bundles slower than V8 in some cases. Fix: ship less JS, test in Safari.
Testing and CI/CD
Lighthouse CI runs on every PR. Fail the build on regressions over a threshold:
YAMLCopy
yaml
.github/workflows/perf.yml
name: Performance
on: [pull_request]
jobs:
lighthouse:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4 with: { node-version: '20' }
- run: npm ci && npm run build
- run: npm run preview & # start the server
- run: npx wait-on http://localhost:4173
- run: npx @lhci/cli@0.13.x autorun --upload.target=temporary-public-storage
plaintext
For per-route testing, list all critical routes in .lighthouserc.json. Run Lighthouse against each, fail on any regression.
Bundle size monitoring with bundlewatch or size-limit:
JSONCopy
json
{
"files": [{ "path": "dist/assets/index-*.js", "maxSize": "200KB" }],
"defaultCompression": "gzip"
}
For RUM in production, sample at 10-100% depending on traffic. Always include the navigation type, route, device class, and connection type in your events so you can slice meaningfully.
Cost and Alternatives
CWV optimization is mostly engineering time, not infrastructure spend. But the levers have costs:
| Lever | Cost | Impact |
|---|---|---|
| Image format optimization (AVIF/WebP) | Engineering time + build pipeline | High on image-heavy sites |
| CDN with edge caching | $20-200/mo depending on traffic | High on global audiences |
| SSR vs CSR | Engineering time + hosting (Node workers vs static) | High on content sites |
| Self-hosting fonts | Negligible | Medium |
| Partytown / web worker for 3p scripts | Engineering time | Medium if heavy 3p |
| Cloudflare Auto Minify, Image Resizing | $5-200/mo | Medium, hands-off |
| Edge DB / Edge rendering (Vercel Edge, Cloudflare Workers) | Per-request pricing | High, but architecture work |
| RUM tooling (Datadog RUM, SpeedCurve, Akamai mPulse) | $50-2000+/mo | Essential for serious work |
For most teams: free tier of Search Console + PageSpeed Insights for field data, Lighthouse CI for lab, and a simple homegrown RUM collector with web-vitals library is enough to start. Upgrade to a paid RUM tool when you're at the scale where you need user-segment slicing.
Real-World Use Cases
- E-commerce product pages. LCP is usually the hero image. Self-host, AVIF, preload, fetchpriority high. We've seen this pattern move LCP from 4.2s to 1.6s on mobile.
- Content sites (news, blogs). SSR is non-negotiable. Preload the headline image. Defer all analytics. Cap JS budget at 100KB initial.
- SaaS dashboards behind auth. CWV matters less for SEO but more for retention. INP is the killer-every chart library you add blocks the main thread.
- Marketing landing pages. These get crawled by Google, so CWV is critical. Strip everything non-essential. No chat widget above the fold. No autoplay video. Static HTML with minimal JS.
- Mobile web for emerging markets. Users on 2G/3G with low-end Android. Ship <100KB initial JS, server-render everything, inline critical CSS, lazy-load all images.
Wrapping Up
Core Web Vitals is one of the few areas of frontend work where the metric is well-defined, the tooling is excellent, and the fixes are mostly known quantities. The hard part isn't understanding what to do-it's having the discipline to measure, prioritize, and push back when product wants to add another 200KB script for a feature nobody uses.
If you take one thing from this: ship less JavaScript. It's the single biggest lever for all three metrics. Everything else-image optimization, font loading, critical CSS-is secondary to the size of your JS bundle.
Originally published on Mango Developer.

Top comments (0)