Back to Home

Web Performance Optimization: Core Web Vitals Guide

3 min read

Master the art of web performance optimization. Learn about Core Web Vitals, performance budgets, and practical techniques to make your websites blazingly fast.

Web Performance Optimization: Core Web Vitals Guide

Performance is crucial for user experience and SEO. This guide covers everything you need to know about optimizing web performance, focusing on Core Web Vitals.

Understanding Core Web Vitals

Core Web Vitals are a set of metrics that measure real-world user experience:

Largest Contentful Paint (LCP)

Measures loading performance. Should occur within 2.5 seconds.

First Input Delay (FID) / Interaction to Next Paint (INP)

Measures interactivity. FID should be less than 100ms, INP less than 200ms.

Cumulative Layout Shift (CLS)

Measures visual stability. Should be less than 0.1.

Performance Optimization Strategies

1. Optimize Images

Images often account for the majority of page weight:

<!-- Use modern formats -->
<picture>
  <source srcset="image.avif" type="image/avif">
  <source srcset="image.webp" type="image/webp">
  <img src="image.jpg" alt="Description" loading="lazy">
</picture>

<!-- Responsive images -->
<img 
  srcset="small.jpg 480w, medium.jpg 800w, large.jpg 1200w"
  sizes="(max-width: 480px) 100vw, (max-width: 800px) 50vw, 25vw"
  src="medium.jpg" 
  alt="Description"
>

2. Minimize JavaScript

Reduce JavaScript bundle size and optimize loading:

// Use dynamic imports for code splitting
const heavyModule = await import('./heavy-module.js');

// Implement lazy loading for components
const LazyComponent = lazy(() => import('./LazyComponent'));

// Optimize third-party scripts
const script = document.createElement('script');
script.src = 'third-party.js';
script.async = true;
document.head.appendChild(script);

3. Optimize CSS

Critical CSS and efficient loading strategies:

<!-- Inline critical CSS -->
<style>
  /* Critical above-the-fold styles */
  .hero { display: flex; align-items: center; }
</style>

<!-- Preload important resources -->
<link rel="preload" href="fonts/main.woff2" as="font" type="font/woff2" crossorigin>

<!-- Load non-critical CSS asynchronously -->
<link rel="preload" href="styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">

Performance Monitoring

Web Vitals Library

import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals';

getCLS(console.log);
getFID(console.log);
getFCP(console.log);
getLCP(console.log);
getTTFB(console.log);

Performance Observer API

// Monitor LCP
new PerformanceObserver((entryList) => {
  for (const entry of entryList.getEntries()) {
    console.log('LCP candidate:', entry.startTime);
  }
}).observe({ type: 'largest-contentful-paint', buffered: true });

// Monitor CLS
new PerformanceObserver((entryList) => {
  for (const entry of entryList.getEntries()) {
    if (!entry.hadRecentInput) {
      console.log('Layout shift:', entry.value);
    }
  }
}).observe({ type: 'layout-shift', buffered: true });

Advanced Techniques

Resource Hints

<!-- DNS prefetch for external domains -->
<link rel="dns-prefetch" href="//example.com">

<!-- Preconnect to critical resources -->
<link rel="preconnect" href="https://fonts.googleapis.com" crossorigin>

<!-- Prefetch likely next navigation -->
<link rel="prefetch" href="/likely-next-page">

Service Worker Caching

// sw.js
const CACHE_NAME = 'app-cache-v1';

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request)
      .then(response => response || fetch(event.request))
  );
});

Performance Budget

Establish and monitor performance budgets:

{
  "budget": [
    {
      "path": "/*",
      "timings": [
        {
          "metric": "first-contentful-paint",
          "budget": 2000
        },
        {
          "metric": "largest-contentful-paint",
          "budget": 2500
        }
      ],
      "resourceSizes": [
        {
          "resourceType": "script",
          "budget": 300
        },
        {
          "resourceType": "total",
          "budget": 1000
        }
      ]
    }
  ]
}

Testing and Tools

  1. Lighthouse: Automated performance audits
  2. WebPageTest: Real-world performance testing
  3. Core Web Vitals: Chrome DevTools and Search Console
  4. Bundle Analyzers: Visualize bundle composition

Conclusion

Performance optimization is an ongoing process that requires continuous monitoring and improvement. By focusing on Core Web Vitals and implementing these strategies, you can significantly improve user experience and search engine rankings.