Lesson 12 of 12 · 10 min · How the browser works
Web performance and Core Web Vitals
What you will learn
- Why performance matters for users and business
- The three Core Web Vitals: LCP, INP and CLS, and their targets
- Measure with Lighthouse, PageSpeed Insights, DevTools and real-user data
- Fix slow images, fonts, JavaScript and CSS
- Use caching, compression and a CDN, and set a performance budget
In simple words
People leave slow pages. On a mid-range phone with a patchy connection, every extra second and every extra megabyte costs visitors. Web performance is the craft of making pages show up quickly, respond to taps immediately and not jump around while loading. Google measures this with three simple numbers called Core Web Vitals, and they also influence how well a page can rank in search.
Words to know
- Core Web Vitals: three measures of loading, interactivity and visual stability.
- Lab data: measurements from a controlled test run, such as Lighthouse.
- Field data: measurements from real users' visits.
- Performance budget: a limit on page weight or timing that the team agrees not to exceed.
Why it matters
- Users: faster pages convert better, are used more, and cost less data. In India many users are on mid-range Android phones and on mobile data with variable speed and limited data plans, so heavy pages are a real barrier.
- Business: studies from large sites consistently link faster load times to higher conversion and lower bounce rates.
- Search: page experience (including Core Web Vitals) is a ranking signal, though content relevance matters more.
- Cost: smaller pages use less bandwidth and server load.
The Core Web Vitals
| Metric | Measures | "Good" (at the 75th percentile of visits) |
|---|---|---|
| LCP Largest Contentful Paint | loading: when the largest visible element (hero image, main heading) is rendered | 2.5 s or less (poor above 4 s) |
| INP Interaction to Next Paint | responsiveness: how quickly the page visually responds to clicks, taps and key presses across the visit | 200 ms or less (poor above 500 ms) |
| CLS Cumulative Layout Shift | visual stability: how much content unexpectedly moves | 0.1 or less (poor above 0.25) |
INP replaced First Input Delay (FID) as a Core Web Vital in March 2024. Other useful metrics: TTFB (Time to First Byte, server and network speed), FCP (First Contentful Paint), TBT (Total Blocking Time, a lab proxy for INP) and Speed Index. A page "passes" when 75 percent of real visits meet the good threshold for all three.
Measuring
- Lighthouse (Chrome DevTools, a tab named Lighthouse, or the command line): a lab audit with scores and specific recommendations. Run it in an incognito window with extensions off, on mobile settings.
- PageSpeed Insights: Lighthouse plus field data from the Chrome User Experience Report (CrUX) for the real URL if it has enough traffic.
- Chrome DevTools Performance panel: record a load or an interaction; find long tasks, layout and paint (the rendering lesson). Throttle CPU 4x and network Slow 4G.
- WebPageTest: detailed tests from real devices and locations (including India), filmstrips and waterfalls.
- Real-user monitoring (RUM): the
web-vitalsJavaScript library sends LCP, INP and CLS from real users to your analytics:
import { onLCP, onINP, onCLS } from "web-vitals";
onLCP(metric => navigator.sendBeacon("/vitals", JSON.stringify(metric)));
onINP(metric => navigator.sendBeacon("/vitals", JSON.stringify(metric)));
onCLS(metric => navigator.sendBeacon("/vitals", JSON.stringify(metric)));
Lab data is reproducible and good for debugging; field data shows what users really experience across devices and networks and is what counts. Use both. Always measure before and after a change.
Improving LCP (loading)
The LCP element is usually a hero image or a heading. Steps:
- Fast server and network: reduce TTFB with caching, a CDN, compression, efficient server code and HTTP/2 or 3; avoid redirects.
- Do not hide the LCP element: do not lazy-load it; do not make it depend on JavaScript (client-rendered content shows late: consider server-side rendering or static generation).
- Prioritise it:
<img ... fetchpriority="high">or<link rel="preload" as="image" href="hero.avif">. - Right-size and compress the image: modern formats (AVIF, WebP),
srcsetandsizes, dimensions, appropriate quality. - Remove render-blocking CSS and JavaScript: inline critical CSS,
deferscripts, load the rest later.
Improving INP (responsiveness)
INP is mostly about JavaScript on the main thread:
- Break up long tasks (over 50 ms): split work and yield to the browser.
- Reduce JavaScript: ship less code; remove unused dependencies; code-split by route; lazy-load components that are not visible.
- Make event handlers fast: do minimal work, then defer the rest (
requestIdleCallback,setTimeout, a worker). - Avoid expensive layout and rendering after an interaction (the previous lesson).
- Move heavy computation to a Web Worker.
- Keep third-party scripts (analytics, chat, ads, tag managers) under control: each costs main-thread time.
- In React: avoid unnecessary re-renders (
memo, stable props, keys), virtualise long lists, use transitions (useTransition) for non-urgent updates.
Improving CLS (stability)
- Reserve space for images and video (
width,heightoraspect-ratio), embeds, ads and banners. - Avoid inserting content above what the user is reading; add banners and notices below or with reserved space.
- Fonts:
font-display: swapwith a metrically similar fallback (size-adjust,ascent-override), preload critical fonts, and self-host or subset them. - Animate with
transform, not by changingtoporheight. - Avoid loading late content that pushes the page down (a cookie banner that appears after the content).
Practical savings
Images (usually the biggest bytes):
- Use AVIF or WebP; resize to the displayed size; compress; use SVG for icons and logos.
loading="lazy"for below-the-fold images,decoding="async".- Serve responsive images with
srcset. - Replace animated GIFs with
<video autoplay muted loop playsinline>(much smaller).
JavaScript:
- Measure the bundle (a bundle analyser such as
vite-bundle-visualizerorsource-map-explorer), remove or replace heavy libraries (use nativefetch,IntlandDateinstead of large helpers), enable tree shaking and code splitting (import("./chart.js")loads on demand), minify, and compress (Brotli). - Ship modern JavaScript (no unnecessary polyfills and transpilation for old browsers).
CSS: remove unused rules, keep critical CSS small, avoid @import chains.
Fonts: limit families and weights, use woff2, subset to needed characters (Latin plus the scripts you use), consider system fonts.
Network and caching:
- Enable Brotli or gzip compression for text.
- Long-lived
Cache-Controlfor hashed static files, revalidation for HTML (the page-load lesson). - A CDN with edge locations near your users (including India).
- HTTP/2 or HTTP/3,
preconnectto critical third-party origins (used sparingly). - Reduce the number of third-party requests.
Rendering strategy: server-side rendering or static generation gives meaningful HTML early; client-only rendering delays LCP and hurts low-end phones, but suits logged-in app screens; streaming and partial hydration (frameworks such as Next.js and Astro) help.
A performance budget
Agree limits and make the build fail when they are exceeded, for example: JavaScript under 170 KB compressed for the first load, LCP under 2.5 s on a mid-range phone on 4G, no image over 200 KB, CLS under 0.1. Tools: Lighthouse CI, bundlesize, and Webpack or Vite size limits in CI. Performance degrades gradually with each added library and script; a budget turns it into a visible decision.
Test like your users
- Use a real mid-range Android phone and a throttled connection; the Chrome DevTools "Slow 4G" and CPU throttling are good approximations.
- Test cold loads (empty cache) and repeat visits.
- Test long sessions and interactions, not only the first load.
- Look at data usage: how many kilobytes does the first screen cost?
- Check results by region and device in RUM.
Common mistakes
- Optimising only for a desktop Lighthouse score.
- Lazy-loading the hero image.
- Large unoptimised images and missing dimensions.
- Shipping huge JavaScript bundles and many third-party scripts.
- Not measuring real users.
- Adding preloads for everything.
- No caching headers or compression.
Try it yourself
- Run Lighthouse in mobile mode on your page and note LCP, INP or TBT and CLS; write down the top three opportunities.
- Convert the hero image to AVIF or WebP, add dimensions and
fetchpriority="high", and re-run. - Defer a script and see the effect on FCP and TBT.
- Add
widthandheightto every image and watch CLS. - Open PageSpeed Insights for a well-known site and compare its field data with its lab data.
Check yourself
What are the three Core Web Vitals and their good thresholds?
LCP of 2.5 seconds or less (loading), INP of 200 milliseconds or less (responsiveness) and CLS of 0.1 or less (visual stability), at the 75th percentile of real visits.
What is the difference between lab and field data?
Lab data comes from controlled test runs such as Lighthouse and is reproducible; field data comes from real users on real devices and networks and shows actual experience.
Why should the LCP image not be lazy-loaded?
Lazy loading delays the image until the browser decides it is near the viewport, which pushes LCP later; load it eagerly and with high priority.
What usually causes poor INP?
Too much JavaScript running on the main thread, such as long tasks and slow event handlers, so the page cannot respond promptly to input.
Interview questions
How would you improve the performance of a slow web page?
Measure with Lighthouse and field data, find the bottleneck, then optimise images (format, size, lazy loading below the fold), reduce and split JavaScript, remove render-blocking resources, enable compression and caching with a CDN, reserve space for layout stability, control third-party scripts, and verify on a real mobile device.
What is Largest Contentful Paint and how do you improve it?
LCP is the time when the largest visible content element renders. Improve server response time, prioritise and optimise the LCP image, remove render-blocking resources and avoid client-side-only rendering of the main content.
What is a performance budget?
A set limit on metrics such as bundle size or LCP that the team commits to, enforced in CI so that regressions are caught early.
Summary
- Core Web Vitals: LCP at most 2.5 s, INP at most 200 ms, CLS at most 0.1 for most real visits.
- Measure with Lighthouse, PageSpeed Insights, DevTools and real-user monitoring, on throttled mobile settings.
- Biggest wins: optimised responsive images, less and deferred JavaScript, reserved space, caching, compression and a nearby CDN.
- Set a performance budget and test on real mid-range phones.
Going deeper
- web.dev: Core Web Vitals: definitions and thresholds.
- web.dev: Learn Performance: a free course.
- MDN: Web performance: guides and best practices.
- web.dev: Optimize Largest Contentful Paint: the step-by-step guide.
See how much of this you can explain
A free mock interview asks you new questions on HTML, CSS and how the web works for Frontend Developer and scores every answer, with what to fix.