Blog.

speed optimization core web vitals

Cover Image for speed optimization core web vitals
SDX VISION
SDX VISION

Core Web Vitals are Google's key metrics for measuring user experience. This guide will teach you how to optimize your website's speed and Core Web Vitals for better performance and rankings.

Understanding Core Web Vitals

The Three Metrics:

1. Largest Contentful Paint (LCP)

  • Target: < 2.5 seconds
  • Measures: Loading performance
  • What It Tracks: Time to render largest content element

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

  • Target: < 100ms (FID) or < 200ms (INP)
  • Measures: Interactivity
  • What It Tracks: Time to respond to user interaction

3. Cumulative Layout Shift (CLS)

  • Target: < 0.1
  • Measures: Visual stability
  • What It Tracks: Unexpected layout shifts

Optimizing Largest Contentful Paint (LCP)

What Affects LCP:

Common LCP Elements:

  • Hero images
  • Large text blocks
  • Video posters
  • Background images
  • Carousel images

Optimization Strategies:

1. Optimize Server Response Time

Target: < 200ms

Methods:

  • Use fast hosting
  • Enable CDN
  • Implement caching
  • Optimize database
  • Use edge computing

Implementation:

# Nginx caching example
location / {
    proxy_cache my_cache;
    proxy_cache_valid 200 1h;
    add_header Cache-Control "public, max-age=3600";
}

2. Eliminate Render-Blocking Resources

CSS:

<!-- Critical CSS inline -->
<style>
  /* Above-the-fold styles */
</style>

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

JavaScript:

<!-- Defer non-critical JS -->
<script src="script.js" defer></script>

<!-- Or async -->
<script src="analytics.js" async></script>

3. Optimize Images

Best Practices:

  • Use modern formats (WebP, AVIF)
  • Compress images
  • Lazy load below-fold
  • Use appropriate sizes
  • Add width/height

Implementation:

<picture>
  <source srcset="image.avif" type="image/avif">
  <source srcset="image.webp" type="image/webp">
  <img src="image.jpg" 
       alt="Description" 
       width="1200" 
       height="600"
       loading="lazy">
</picture>

4. Preload Key Resources

Preload Critical Resources:

<link rel="preload" href="hero-image.jpg" as="image">
<link rel="preload" href="font.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="critical.css" as="style">

5. Use Resource Hints

DNS Prefetch:

<link rel="dns-prefetch" href="//fonts.googleapis.com">

Preconnect:

<link rel="preconnect" href="https://api.example.com">

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

What Affects FID/INP:

Common Causes:

  • Heavy JavaScript execution
  • Long tasks blocking main thread
  • Large JavaScript bundles
  • Third-party scripts
  • Inefficient event handlers

Optimization Strategies:

1. Reduce JavaScript Execution Time

Code Splitting:

// Dynamic imports
const module = await import('./heavy-module.js');

Minimize JavaScript:

  • Remove unused code
  • Tree shaking
  • Code minification
  • Bundle optimization

2. Break Up Long Tasks

Web Workers:

// Offload heavy processing
const worker = new Worker('worker.js');
worker.postMessage(data);

Task Scheduling:

// Break up long tasks
function processInChunks(items, chunkSize) {
  let index = 0;
  function processChunk() {
    const chunk = items.slice(index, index + chunkSize);
    chunk.forEach(processItem);
    index += chunkSize;
    if (index < items.length) {
      setTimeout(processChunk, 0);
    }
  }
  processChunk();
}

3. Optimize Event Handlers

Use Passive Listeners:

element.addEventListener('scroll', handler, { passive: true });

Debounce/Throttle:

// Debounce
function debounce(func, wait) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

// Usage
const debouncedHandler = debounce(handler, 300);

4. Minimize Third-Party Scripts

Strategies:

  • Load asynchronously
  • Defer non-critical
  • Use iframes
  • Consider alternatives
  • Monitor impact

5. Optimize Main Thread

Avoid:

  • Synchronous operations
  • Blocking operations
  • Heavy computations
  • Large DOM manipulations

Optimizing Cumulative Layout Shift (CLS)

What Causes CLS:

Common Causes:

  • Images without dimensions
  • Ads/embeds without space
  • Web fonts causing FOIT/FOUT
  • Dynamically injected content
  • Animations

Optimization Strategies:

1. Set Image Dimensions

Always Specify:

<img src="image.jpg" 
     width="800" 
     height="600" 
     alt="Description">

CSS Aspect Ratio:

img {
  aspect-ratio: 16 / 9;
  width: 100%;
  height: auto;
}

2. Reserve Space for Dynamic Content

Ads/Embeds:

<div style="min-height: 250px; width: 100%;">
  <!-- Ad will load here -->
</div>

3. Optimize Web Fonts

Preload Fonts:

<link rel="preload" href="font.woff2" as="font" type="font/woff2" crossorigin>

Font Display:

@font-face {
  font-family: 'MyFont';
  src: url('font.woff2') format('woff2');
  font-display: swap; /* or optional, fallback */
}

4. Avoid Inserting Content Above Existing

Best Practice:

  • Reserve space
  • Use transforms for animations
  • Avoid inserting above content
  • Use fixed/v sticky positioning carefully

Comprehensive Speed Optimization

1. Image Optimization

Techniques:

  • Use WebP/AVIF formats
  • Compress images (TinyPNG, ImageOptim)
  • Implement lazy loading
  • Use responsive images
  • Optimize file sizes

Lazy Loading:

<img src="image.jpg" loading="lazy" alt="Description">

2. CSS Optimization

Strategies:

  • Minify CSS
  • Remove unused CSS
  • Critical CSS inline
  • Defer non-critical
  • Use CSS containment

Critical CSS:

<style>
  /* Above-the-fold critical styles */
</style>
<link rel="stylesheet" href="non-critical.css" media="print" onload="this.media='all'">

3. JavaScript Optimization

Optimizations:

  • Minify and compress
  • Code splitting
  • Tree shaking
  • Lazy load modules
  • Remove unused code

Bundle Analysis:

# Analyze bundle
npm run build -- --analyze

4. Caching Strategy

Browser Caching:

location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
}

Service Workers:

// Cache static assets
self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open('v1').then((cache) => {
      return cache.addAll([
        '/',
        '/styles.css',
        '/script.js'
      ]);
    })
  );
});

5. CDN Implementation

Benefits:

  • Faster content delivery
  • Reduced server load
  • Global distribution
  • Better performance

Setup:

  • Choose CDN provider
  • Configure origin
  • Set up caching rules
  • Enable compression

6. Database Optimization

Techniques:

  • Optimize queries
  • Add indexes
  • Use caching
  • Database cleanup
  • Query optimization

Testing and Monitoring

Tools:

1. Google PageSpeed Insights:

  • Core Web Vitals scores
  • Optimization suggestions
  • Field and lab data

2. Chrome DevTools:

  • Performance profiling
  • Network analysis
  • Lighthouse audits

3. WebPageTest:

  • Detailed analysis
  • Waterfall charts
  • Multiple locations

4. Real User Monitoring:

  • Actual user metrics
  • Real-world performance
  • Continuous monitoring

Monitoring Setup:

1. Google Search Console:

  • Core Web Vitals report
  • Field data
  • Issue identification

2. Analytics:

  • Page load times
  • User behavior
  • Performance metrics

Optimization Checklist

  • [ ] LCP < 2.5 seconds
  • [ ] FID/INP < 100ms/200ms
  • [ ] CLS < 0.1
  • [ ] Server response < 200ms
  • [ ] Images optimized
  • [ ] CSS minified
  • [ ] JavaScript optimized
  • [ ] Caching enabled
  • [ ] CDN configured
  • [ ] Fonts optimized
  • [ ] Third-party scripts optimized
  • [ ] Mobile optimized

Common Issues and Solutions

Issue 1: Slow LCP

Solutions:

  • Optimize server response
  • Preload key resources
  • Optimize images
  • Minimize render-blocking

Issue 2: High FID/INP

Solutions:

  • Reduce JavaScript execution
  • Optimize event handlers
  • Use web workers
  • Minimize third-party scripts

Issue 3: High CLS

Solutions:

  • Set image dimensions
  • Reserve space for dynamic content
  • Optimize fonts
  • Avoid layout shifts

Best Practices

  1. Measure First: Use tools to identify issues
  2. Optimize Critical Path: Focus on above-the-fold
  3. Progressive Enhancement: Build from mobile up
  4. Regular Testing: Monitor continuously
  5. Iterate: Continuous improvement

Next Steps

  1. Audit Performance: Use PageSpeed Insights
  2. Identify Issues: Focus on Core Web Vitals
  3. Implement Optimizations: Follow this guide
  4. Test Changes: Verify improvements
  5. Monitor Continuously: Track performance

Thanks for reading the blog. If you want more help, do contact us at https://sdx.vision