Core Web Vitals Fundamentals
By the end of this lesson you will be able to explain the three Core Web Vitals and their thresholds, tell field data from lab data, trace a slow metric back to the HTML that causes it, and measure all three yourself with PerformanceObserver and the web-vitals library.
What you should know first: HTML Performance Optimization, Lazy Loading & Image Optimization and Browser Rendering Fundamentals. They introduced the metrics; this lesson explains how each is calculated and measured. Thresholds were checked on web.dev in November 2026.
Three questions about user experience
Imagine lunch at a busy dhaba in Jaipur. How soon does your thali arrive? When you call the waiter, how quickly does he respond, every single time? Does anyone bump your table while you eat? The Core Web Vitals ask the same three questions about a page.
| Metric | Question | Good | Needs improvement | Poor |
|---|---|---|---|---|
| LCP, Largest Contentful Paint | When does the main content appear? | 2.5 s or less | up to 4 s | over 4 s |
| INP, Interaction to Next Paint | How fast does the page respond to clicks, taps and keys? | 200 ms or less | up to 500 ms | over 500 ms |
| CLS, Cumulative Layout Shift | How much does the layout jump unexpectedly? | 0.1 or less | up to 0.25 | over 0.25 |
A page passes when the 75th percentile of real visits is good for all three, measured separately for phones and desktops. That means three out of four visits were at least that good, so the slower phones of real visitors decide your score.
Field data and lab data
Field data comes from real users on real devices and networks. It is also called RUM (real user monitoring). Lab data comes from a test you run on one machine with fixed settings, such as Lighthouse in Chrome DevTools.
| Field data | Lab data | |
|---|---|---|
| Source | Real visits | One simulated visit |
| Tools | Chrome UX Report (CrUX), PageSpeed Insights, Search Console, your own RUM script | Lighthouse, DevTools Performance panel |
| INP | Measured from real interactions | Not measured: no one clicks; Total Blocking Time is a rough stand-in |
The Chrome UX Report (CrUX) is Google's public field dataset from opted-in Chrome users, over a rolling 28-day window, for sites with enough traffic. PageSpeed Insights shows CrUX data above a Lighthouse lab run, and Search Console's Core Web Vitals report groups similar URLs as good, needs improvement or poor. CrUX has no Safari data, so collect your own if many visitors use iPhones.
Google says its ranking systems use Core Web Vitals, but helpful content matters far more, and good scores never guarantee a ranking. Improve them because users leave slow, jumpy pages.
LCP: what slows the main content
The LCP element is the largest image or text block visible in the first screen: an <img>, the poster of a <video>, an element with a CSS url() background, or a block of text. The browser keeps reporting larger candidates until the user taps, scrolls or presses a key.
LCP time splits into four parts. Each has typical HTML causes:
| Part | Meaning | HTML causes and fixes |
|---|---|---|
| Time to first byte | The server's response time | Slow server code; use caching and a CDN |
| Resource load delay | Gap before the image starts downloading | Image hidden in CSS, added by JavaScript or marked loading="lazy"; use a plain <img> with fetchpriority="high", or preload a CSS image |
| Resource load duration | Download time | Oversized file; use srcset, AVIF or WebP |
| Element render delay | Gap between download and display | Render-blocking CSS and scripts in the head; use defer and small CSS; web fonts hiding text, fix with font-display: swap |
Resource load delay is usually the easiest win: let the browser find the hero image in the HTML itself.
INP: why a tap feels slow
The browser runs JavaScript, handles input and paints on one main thread, like a single ticket clerk at a small station: if the clerk is busy, the next passenger waits. Each interaction has three phases:
- Input delay: waiting for the main thread to finish whatever it was doing.
- Processing: running your event handlers.
- Presentation delay: the browser recalculating styles and layout and painting the next frame.
INP reports roughly the slowest interaction of the visit (on pages with very many interactions, a few extreme ones are ignored). A long task is any job that blocks the main thread for more than 50 ms.
Causes: scripts loaded without defer, third-party widgets, handlers doing heavy work before updating the screen, and a huge DOM that slows every layout. Fixes: update the screen first and defer other work until after the next paint, split long jobs (scheduler.yield() where supported, otherwise setTimeout), and keep the DOM lean.
CLS: why the page jumps
A layout shift happens when a visible element changes position between two frames. Each shift gets a score: the fraction of the screen affected multiplied by the fraction of the screen the elements moved. Shifts that happen within 500 ms of a tap or key press do not count, because the user expected a change.
Shifts are grouped into session windows (shifts less than 1 second apart, at most 5 seconds long), and CLS is the score of the worst window.
HTML causes and fixes:
- Images, iframes and videos without size. Add
widthandheight, or CSSaspect-ratio. - Ads, embeds and banners inserted above content. Reserve space with
min-height, or show notices as overlays that do not push content. - Web fonts that swap in with different sizes. Pick a fallback font with similar metrics, or use the
size-adjustdescriptor in@font-face. - Animating
top,left,widthorheight. Animatetransforminstead; it does not move other elements.
Step 1: watch LCP and CLS happen
PerformanceObserver lets a page subscribe to performance entries. observe({ type, buffered: true }) asks for one entry type, including earlier entries. Feature-detect with PerformanceObserver.supportedEntryTypes.
This page simulates a slow network: an offer banner appears after 0.8 seconds and a photo without dimensions after 1.6 seconds.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Watch LCP and CLS</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; max-width: 40rem; }
img { display: block; max-width: 100%; height: auto; }
.offer { background: #ffe0b2; padding: 12px; margin: 0; }
.fixed .slot { min-height: 48px; } /* reserved space for the offer */
pre { background: #f4f4f4; padding: 8px; white-space: pre-wrap; }
</style>
</head>
<body>
<div class="slot" id="slot"></div>
<h1>Kochi houseboat stays</h1>
<img id="hero" alt="Hills and a river at sunrise">
<p>One night on the backwaters with dinner from ₹6,500.</p>
<pre id="log"></pre>
<script>
const FIXED = false; // change to true and run again
const log = (text) => { document.querySelector("#log").textContent += text + "\n"; };
const hero = document.querySelector("#hero");
if (FIXED) {
document.body.classList.add("fixed");
hero.width = 800; // same as width="800" height="500" in the HTML
hero.height = 500;
}
const types = PerformanceObserver.supportedEntryTypes;
if (types.includes("largest-contentful-paint")) {
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
const what = entry.element ? entry.element.tagName.toLowerCase() : "(element removed)";
log("LCP candidate: " + what + " at " + Math.round(entry.startTime) + " ms");
}
}).observe({ type: "largest-contentful-paint", buffered: true });
}
let total = 0;
if (types.includes("layout-shift")) {
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.hadRecentInput) continue; // shifts right after a tap or key press do not count
total += entry.value;
log("Layout shift: " + entry.value.toFixed(3) + " (running total " + total.toFixed(3) + ")");
}
}).observe({ type: "layout-shift", buffered: true });
} else {
log("This browser does not report layout-shift entries (Chromium browsers do).");
}
// Simulate a slow network: the offer and the photo arrive late
setTimeout(() => {
const offer = document.createElement("p");
offer.className = "offer";
offer.textContent = "Onam offer: free breakfast this week";
document.querySelector("#slot").append(offer);
}, 800);
setTimeout(() => { hero.src = "https://course.ethicscomputer.in/assets/samples/landscape.svg"; }, 1600);
</script>
</body>
</html>In Chrome or Edge you should see an LCP candidate for the h1, then layout shift lines when the banner and the photo arrive. The photo never becomes the LCP element: the sample is a tiny 756-byte drawing, and Chromium skips such low-content images as placeholders. A real photo would.
Now change FIXED to true and run again. The banner's slot is reserved with min-height and the image has dimensions, so no layout shift lines appear. This demo adds up every shift; real CLS uses the worst session window. PerformanceObserver Integration covers the API in depth.
Step 2: measure interaction latency
Interactions are measured with the Event Timing API: entry type event. Entries that belong to a real interaction carry an interactionId. durationThreshold: 16 asks for every event lasting 16 ms or more; shorter events are not reported. Durations are rounded to 8 ms.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Measure interaction latency</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; }
button { padding: 8px 14px; margin-inline-end: 8px; }
table { border-collapse: collapse; margin-top: 12px; }
th, td { border: 1px solid #ccc; padding: 4px 8px; text-align: end; }
th:first-child, td:first-child { text-align: start; }
.poor { background: #ffcdd2; }
</style>
</head>
<body>
<h1>Isha's Pune bakery: rava cake, ₹349</h1>
<button type="button" id="slow">Add to cart (slow)</button>
<button type="button" id="fast">Add to cart (fast)</button>
<p id="cart" aria-live="polite">Cart: 0 items</p>
<table>
<thead><tr><th>Button</th><th>Total ms</th><th>Input delay</th><th>Handlers</th><th>Until paint</th></tr></thead>
<tbody id="rows"></tbody>
</table>
<script>
let items = 0;
const showCart = () => { document.querySelector("#cart").textContent = "Cart: " + items + " items"; };
function heavyWork() { // stands in for analytics, recalculations and so on
const end = performance.now() + 300;
while (performance.now() < end) {}
}
document.querySelector("#slow").addEventListener("click", () => {
heavyWork(); // the user waits for this before seeing anything
items++;
showCart();
});
document.querySelector("#fast").addEventListener("click", () => {
items++;
showCart(); // update the screen first
requestAnimationFrame(() => setTimeout(heavyWork, 0)); // heavy work after the next paint
});
// Event Timing: one row per interaction, keeping its longest event (the later one on a tie)
const rows = new Map();
new PerformanceObserver((list) => {
for (const e of list.getEntries()) {
if (!e.interactionId) continue; // not a click, tap or key press
const old = rows.get(e.interactionId);
if (old && old.duration > e.duration) continue;
const tr = old?.tr ?? document.querySelector("#rows").insertRow();
tr.replaceChildren();
const cells = [
e.target?.id || e.name,
e.duration,
Math.round(e.processingStart - e.startTime),
Math.round(e.processingEnd - e.processingStart),
Math.round(e.startTime + e.duration - e.processingEnd),
];
for (const value of cells) tr.insertCell().textContent = value;
tr.className = e.duration > 200 ? "poor" : "";
rows.set(e.interactionId, { duration: e.duration, tr });
}
}).observe({ type: "event", durationThreshold: 16, buffered: true });
</script>
</body>
</html>Click each button a few times. The slow button shows about 300 ms in "Handlers" and a red row. The fast button updates the cart first and schedules the heavy work after the next paint with requestAnimationFrame plus setTimeout, so its rows show a few tens of milliseconds. The work still happens; the user just does not wait for it. Two very quick clicks on the fast button may show input delay, because the deferred work is still running, which is why long jobs should also be split.
Measuring real users with the web-vitals library
The raw APIs have many edge cases, such as back/forward cache restores and background tabs. Google's open-source web-vitals library (version 5, checked November 2026) handles them and measures each metric the way CrUX does. Install it with npm install web-vitals and send each result to your server:
import { onCLS, onINP, onLCP } from "web-vitals";
function sendToAnalytics(metric) {
const body = JSON.stringify({
name: metric.name, // "CLS", "INP" or "LCP"
value: metric.value, // milliseconds for LCP and INP, a score for CLS
rating: metric.rating, // "good", "needs-improvement" or "poor"
id: metric.id, // unique per page load, to remove duplicates
page: location.pathname,
});
navigator.sendBeacon("/api/vitals", body); // still delivered while the page unloads
}
onCLS(sendToAnalytics);
onINP(sendToAnalytics);
onLCP(sendToAnalytics);One beacon your server might receive:
{"name":"LCP","value":2310.4,"rating":"good","id":"(unique id)","page":"/sarees/banarasi/"}Store these and compute the 75th percentile per page type and device. The web-vitals/attribution build adds details such as which element was the LCP element. CLS and INP are often reported only when the page is hidden, so do not expect values at load.
Common mistakes
- Judging by one Lighthouse run on a fast laptop. Field data at the 75th percentile is what counts.
- Still optimising for FID. INP replaced it in March 2024.
- Inserting banners above content without reserved space. Every visitor's page jumps.
- Heavy work in click handlers before updating the screen. Paint first, then work.
Interview questions
1. What are the Core Web Vitals and their "good" thresholds?
LCP measures loading (2.5 s or less), INP measures responsiveness (200 ms or less) and CLS measures visual stability (0.1 or less). Each is judged at the 75th percentile of real page loads, separately for mobile and desktop.
2. What is the difference between field data and lab data?
Field data comes from real users (CrUX or your own RUM script) on real devices and networks. Lab data comes from a controlled test like Lighthouse and is best for debugging. INP needs real interactions, so it is a field metric.
3. Why did INP replace FID?
FID measured only the input delay of the first interaction. INP covers every interaction and all three phases up to the next paint, so it reflects responsiveness throughout the visit.
4. Name three HTML causes of poor CLS and their fixes.
Images without width and height (add them), banners inserted above content (reserve space or use overlays) and web fonts swapping with different metrics (use matching fallbacks or size-adjust).
5. How would you improve a slow LCP caused by a hero image?
Use an <img> in the HTML instead of a CSS background, remove loading="lazy", add fetchpriority="high", and serve a correctly sized modern format with srcset. Remove render-blocking scripts from the head.
Key points
- LCP, INP and CLS measure loading, responsiveness and visual stability; good is 2.5 s, 200 ms and 0.1 at the 75th percentile.
- INP replaced FID in March 2024 and measures every interaction up to the next paint.
- Field data (CrUX, RUM) shows real experience; lab data (Lighthouse) helps you debug.
- LCP suffers from late-discovered images, big files and render-blocking resources.
- INP suffers from long tasks; update the screen first and split or defer heavy work.
- CLS suffers from unsized media and inserted content; reserve space and animate
transform.
Exercise
Kabir's Rohtak sports shop page has a hero image set as a CSS background, a cookie banner inserted at the top after one second, a product photo with no dimensions, and an "Add to cart" handler that recalculates every price on the page (about 400 ms) before updating the cart count. For each problem, name the metric it hurts and write the fixed HTML or JavaScript. Then add a PerformanceObserver that logs every largest-contentful-paint entry.
Show solution
<!-- LCP: a real img that the browser finds early -->
<img src="/img/cricket-bats-hero.avif" alt="Cricket bats on display" width="1200" height="600" fetchpriority="high">
<!-- CLS: the cookie notice overlays the page instead of pushing it down -->
<div class="cookie-notice" style="position: fixed; inset-block-end: 0; inset-inline: 0;">...</div>
<!-- CLS: the product photo reserves its space -->
<img src="/img/kashmir-willow-bat.webp" alt="Kashmir willow bat" width="800" height="800" loading="lazy">
<script>
// INP: show the result first, recalculate after the next paint
const addToCart = document.querySelector("#add-to-cart");
const cartCount = document.querySelector("#cart-count");
addToCart.addEventListener("click", () => {
cartCount.textContent = Number(cartCount.textContent) + 1;
requestAnimationFrame(() => setTimeout(recalculatePrices, 0));
});
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log("LCP candidate", entry.element, Math.round(entry.startTime));
}
}).observe({ type: "largest-contentful-paint", buffered: true });
</script>The background image delayed LCP; the inserted banner and the unsized photo caused CLS; the 400 ms handler caused a poor INP. If recalculatePrices stays slow, split it into smaller tasks too.
Quick Quiz
1. What is the "good" threshold for INP?
INP is good at 200 ms or less and poor above 500 ms.
2. Which metric did INP replace in March 2024?
FID measured only the first interaction's input delay.
3. Why can't a Lighthouse lab run report INP?
Lab tools use Total Blocking Time as a rough stand-in.
4. A shift happens 200 ms after the user taps "Show more". Does it count toward CLS?
Expected changes right after input are not counted as unexpected shifts.
Learn HTML with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
