Lesson 30 / 32
Optimizing for Web Vitals
Specific techniques to improve LCP, FID, and CLS.
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
import {getCLS, getFID, getFCP, getLCP, getTTFB} from 'web-vitals';
// Send metrics to your analytics
cls(data => console.log('CLS:', data.value));
fid(data => console.log('FID:', data.value));
fcp(data => console.log('FCP:', data.value));
lcp(data => console.log('LCP:', data.value));
ttfb(data => console.log('TTFB:', data.value));
// Track with Google Analytics
function sendMetric(name, value) {
gtag('event', name, {'value': value});
}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.