DEV Community

Deepika
Deepika

Posted on • Edited on

Core Web Vitals: What They Are & How to Improve Your Site’s Performance

Image description
Core Web Vitals are a set of key performance metrics defined by Google to measure a website's speed, interactivity, and visual stability. These metrics play a crucial role in providing a good user experience and are essential for SEO rankings.

Tools to Measure Website Performance
Several tools are available to analyze and improve website performance:

  1. Google PageSpeed Insights
  2. Lighthouse (Chrome DevTools)
  3. Web Vitals Chrome Extension
  4. Google Search Console
  5. Core Web Vitals Metrics

1. Largest Contentful Paint (LCP) — Measures Loading Performance

LCP measures the time taken to load and render the largest visible content element (e.g., an image, video, or text block) within the viewport. It is a key indicator of how quickly users perceive a page to load.

Ideal LCP: Less than 2.5 seconds.

How to Optimize LCP

1. Optimize Images

  • Use next-generation image formats such as WebP and AVIF instead of JPEG/PNG.
  • Lazy-load non-critical images using the loading="lazy" attribute.
<img src="image.webp" alt="Lazy Loaded Image" loading="lazy" width="600" height="400"> 
Enter fullscreen mode Exit fullscreen mode
  • Do not lazy-load above-the-fold images to ensure faster rendering.
  • Use responsive images (srcset) to serve different sizes for different screen resolutions.
<img src="image.jpg" srcset="image-480w.jpg 480w, image-800w.jpg 800w, image-1200w.jpg 1200w" sizes="(max-width: 600px) 480px, (max-width: 1200px) 800px, 1200px" alt="Responsive image"> 
Enter fullscreen mode Exit fullscreen mode
  • Enable efficient caching by setting a long cache expiration for static images.

2. Reduce Render-Blocking Resources

  • Minimize CSS and JavaScript blocking by:
    Deferring non-critical JavaScript (defer or async).
    Use defer for scripts that modify the DOM (main.js, app.js).
    Use async for scripts that are independent (analytics.js, ads.js).

  • Removing unused CSS using tools like PurgeCSS.

  • Using Critical CSS for above-the-fold content.

3. Optimize Fonts

  • Preload important fonts for faster rendering.
 <link rel="preload" href="fonts/my-font.woff2" as="font" type="font/woff2" crossorigin="anonymous"> 
Enter fullscreen mode Exit fullscreen mode
  • Use font-display: swap; to avoid render delays.
@font-face { font-family: 'MyCustomFont'; src: url('/fonts/MyCustomFont.woff2') format('woff2'), url('/fonts/MyCustomFont.woff') format('woff'); font-weight: normal; font-style: normal; font-display: swap; } 
Enter fullscreen mode Exit fullscreen mode
  • Self-host fonts instead of relying on external services to reduce dependency on third-party networks.

4. Optimize JavaScript Execution

  • Minimize long-running scripts by breaking them into smaller tasks.
  • Avoid excessive DOM manipulations.
  • Defer third-party scripts such as analytics, ads, and social media embeds.

5. Prioritize Above-the-Fold Content

  • Ensure that the LCP element loads first without being delayed by other resources.
  • Avoid dependency on slow third-party scripts for LCP elements.

2. Interaction to Next Paint (INP) — Measures Interactivity

INP (previously FID - First Input Delay) measures the time between a user's first interaction (e.g., clicking a button or link) and the browser's response. It assesses a website's interactivity and responsiveness.

Ideal INP: Less than 200ms.

How to Optimize INP

1. Reduce JavaScript Execution Time

  • Minimize long tasks by breaking them into smaller chunks.
  • Defer non-essential JavaScript (defer or async).
  • Use Web Workers for background tasks to prevent main-thread blocking.

2. Optimize Third-Party Scripts

  • Limit the use of third-party scripts such as ads, social media widgets, and analytics.
  • Load third-party scripts asynchronously.
<script async src="https://www.example.com/"></script> 
Enter fullscreen mode Exit fullscreen mode

3. Reduce Main Thread Work

  • Minimize reflows and repaints by optimizing CSS and layout.
  • Use requestIdleCallback() to schedule non-critical tasks.
  • Use efficient JavaScript frameworks, such as React with Concurrent Mode.
  • Use Web Workers for Heavy Computation **Js file**
const worker = new Worker('worker.js'); worker.postMessage({ data: "Heavy Task" }); worker.onmessage = function (event) { console.log("Processed result:", event.data); }; 
Enter fullscreen mode Exit fullscreen mode

**worker.js**

self.onmessage = function (event) { const result = heavyComputation(event.data); self.postMessage(result); }; function heavyComputation(data) { // Simulate heavy calculations return data + " processed"; } 
Enter fullscreen mode Exit fullscreen mode

4. Optimize Event Listeners

  • Avoid heavy computations in input event handlers (keydown, click, etc.). Use passive event listeners for scroll and touch events:
document.addEventListener('scroll', handler, { passive: true }); 
Enter fullscreen mode Exit fullscreen mode
  • Use debounce to optimize the event listeners
function debounce(func, delay) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => func.apply(this, args), delay); }; } // Example usage: Optimizing an input field event const searchInput = document.getElementById("search"); searchInput.addEventListener( "input", debounce((event) => { console.log("Search:", event.target.value); }, 300) ); 
Enter fullscreen mode Exit fullscreen mode

5. Improve Web Performance Techniques

  • Utilize a Content Delivery Network (CDN) for faster content delivery.
  • Enable Gzip/Brotli compression to reduce page size.
  • Reduce DOM size to prevent excessive processing.
  • Minimize the css and js file using gulp/webpack

3. Cumulative Layout Shift (CLS) — Measures Visual Stability

CLS measures unexpected shifts in visible content while a page is loading. It impacts the user experience by ensuring that elements remain visually stable.

Ideal CLS: Less than 0.1.

How to Optimize CLS

1. Set Explicit Width & Height for Images & Videos

  • Always define width and height attributes in <img> and <video> tags to prevent layout shifts.
  • Use aspect-ratio in CSS to reserve space before images load.
img { width: 100%; height: auto; aspect-ratio: 16 / 9; } 
Enter fullscreen mode Exit fullscreen mode

2. Reserve Space for Ads, Embeds, and Iframes

  • Use min-height in CSS to allocate space for ads and iframes.
  • Avoid dynamically inserting ads that push content down.
.ad-slot { min-height: 250px; /* Reserve space */ background: #f0f0f0; } 
Enter fullscreen mode Exit fullscreen mode

3. Avoid Dynamically Injected Content Above Existing Content

  • Avoid banners or pop-ups that push content down.
  • Use position: fixed or position: absolute for pop-ups to prevent layout shifts.

4. Optimize Fonts to Prevent FOUT/FOIT

  • Use font-display: swap; in CSS to prevent text shifts.
  • Preload fonts for faster rendering.
<link rel="preload" href="fonts/my-font.woff2" as="font" type="font/woff2" crossorigin="anonymous"> 
Enter fullscreen mode Exit fullscreen mode

5. Use Stable Animations & Transitions

  • Avoid animations that cause layout shifts.
  • Use transform: translate() instead of modifying layout properties (width, height, margin).
.animated-element { transform: translateY(10px); transition: transform 0.3s ease-in-out; } 
Enter fullscreen mode Exit fullscreen mode

Conclusion
Optimizing Core Web Vitals is essential for providing a seamless and engaging user experience. By following these best practices, you can improve your site's performance, enhance user satisfaction, and boost your search engine rankings.

Top comments (0)