Lesson 32 / 34

Optimizing for Web Vitals

Apply specific techniques to improve LCP, INP and CLS, including image loading, server rendering and layout stability.

By · 15 years in web development · Updated 1 Oct 2026

Improving LCP (Largest Contentful Paint)

LCP measures when the largest content element (image, heading, video) becomes visible. Improve it by: optimizing server response time, using a CDN, lazy-loading off-screen images, reducing CSS/JS, using system fonts, and prefetching critical resources.

Reducing CLS (Cumulative Layout Shift)

CLS is visual jank — buttons or text moving unexpectedly. Prevent it by: always specifying image/video dimensions, avoiding pop-ups that push content down, using font-display: swap, and avoiding late-loaded content above the fold.

Web Vitals monitoring code

Use the web-vitals library to measure real user metrics.

// Import Web Vitals (v3+ API)
import {onCLS, onINP, onFCP, onLCP, onTTFB} from 'web-vitals';

// Send metrics to your analytics
function sendMetric({name, value}) {
  gtag('event', name, {value: Math.round(name === 'CLS' ? value * 1000 : value)});
}

onCLS(sendMetric);
onINP(sendMetric);
onFCP(sendMetric);
onLCP(sendMetric);
onTTFB(sendMetric);

Use Intersection Observer for lazy loading

Don't load all images at once. Use Intersection Observer to lazy load images below the fold, reducing LCP and improving performance.

Server-side rendering for LCP

SSR ensures the largest contentful element (headline, hero image) is in the initial HTML, loaded immediately. CSR waits for JS to execute, delaying LCP.