Images play a crucial role in enhancing the user experience on websites. However, if not managed properly, they can significantly impact your site’s performance, SEO, and cloud costs. Poorly optimized images can lead to slow load times and high bandwidth usage, affecting your site’s Web Vitals — key metrics Google uses to evaluate page performance.

Key Metrics:

 – Largest Contentful Paint (LCP)

 – Interaction to Next Paint (INP)

 – Cumulative Layout Shift (CLS)

 

By optimizing images, you can improve user satisfaction and engagement, reduce bounce rates, and increase conversion rates. Properly managed images also save on storage and bandwidth costs. This article offers a comprehensive guide to web image optimization techniques for 2024, including image compression, responsive images, lazy loading, and serving images.

Image Formats in 2024

  AVIF: Today’s King

 – Advantages: Superior compression and quality, supports both lossy and lossless compression, transparency, and animated images.

 – Use Cases: Photographs and complex images, graphics requiring transparency, animated images.



  WebP vs AVIF

 – Advantages of WebP: Versatile, supports lossy and lossless compression, transparency, animation, and is widely supported by older browsers.

 – Drawbacks of AVIF: Slower encoding due to complex algorithms but offers better compression.



  SVG (Scalable Vector Graphics)

 – Advantages: Resolution-independent, infinitely scalable, ideal for icons, logos, and graphics.

 – Use Cases: Icons, logos, scalable graphics, and illustrations.



  PNG

 – Advantages: Universal compatibility, lossless quality, supports transparency.

 – Use Cases: Projects requiring support across all browsers, lossless images, simple graphics needing transparency.

Summary of Formats

AD 4nXcA4b2 e8wyjRABUKs1X772MnT7llrx1d3GWCSovoNcC ul64hyGXW 8ipsGcoBqOARxJZ6vNFdaOq 2vmC9BfHBgHTsSXcjaxQmeycw3Rt3rc7O8i4fSrQdY8Xf02xq33L mag?key=Hosw0PQmfvQT1q1HGU5n8w

Image Compression

  Lossless vs Lossy Compression

 If slight quality loss is acceptable, lossy compression can significantly reduce the file size, making web pages load faster without noticeable degradation to the user.



  Incremental Encoding in AVIF

 Allows images to be loaded progressively, enhancing the perceived load time but may slightly increase the file size. This technique is particularly beneficial for large images as it ensures that users can start seeing the image even if it’s not fully downloaded.

Responsive Images with `` and `srcset`

Using `<picture>` Element

 Provides a flexible way to specify multiple image sources based on various conditions like media queries. This helps in serving the right image for the right device.

 

 “`html

 <picture>

 <source media=”(min-width: 800px)” srcset=”large.jpg”>

 <source media=”(min-width: 400px)” srcset=”medium.jpg”>

 <img src=”small.jpg” alt=”Example image”>

 </picture>

 “`

 

  Using `srcset` Attribute

 Allows you to define multiple image sources along with their sizes, letting the browser choose the best image based on screen size and resolution.

 

 “`html

 <img

   src=”default.jpg”

   srcset=”small.jpg 480w, medium.jpg 800w, large.jpg 1200w”

   sizes=”(max-width: 600px) 480px, (max-width: 900px) 800px, 1200px”

   alt=”Responsive image”

 >

 “`

 

  Real-world Example

 A comprehensive example for serving different images based on device views:

 

 “`html

 <picture>

 <source media=”(min-width: 1200px)” srcset=”desktop.jpg 1x, desktop@2x.jpg 2x”>

 <source media=”(min-width: 768px)” srcset=”tablet.jpg 1x, tablet@2x.jpg 2x”>

 <source media=”(max-width: 767px)” srcset=”mobile.jpg 1x, mobile@2x.jpg 2x”>

 <img

  src=”fallback.jpg”

  srcset=”mobile.jpg 480w, tablet.jpg 800w, desktop.jpg 1200w”

  sizes=”(max-width: 767px) 480px, (max-width: 1199px) 800px, 1200px”

  alt=”Responsive image”

 >

 </picture>

 “`

 

  Lazy Loading

 

  Native Lazy Loading

 Modern browsers support native lazy loading with the `loading` attribute, making it easier to implement this optimization technique.

 

 “`html

 <img src=”image.jpg” alt=”Example image” loading=”lazy”>

 “`

 

  Recommendations

 – Use `loading=lazy` only for images outside the initial viewport to improve initial page load times.

 – Define dimension attributes (width and height) to prevent layout shifts, improving Cumulative Layout Shift (CLS) scores.

Networking: HTTP Protocol, Client-side Caching, CDN

  HTTP/2 and HTTP/3

 Enable parallel downloads and reduce latency, significantly improving load times for your users. These protocols are the latest evolution in web performance.

 

  Setting Cache-Control Headers

 Define caching duration based on image change frequency. Proper caching setup ensures that frequently accessed images are served quickly to the user without unnecessary downloads.

 

 “`nginx

 location ~ \\.(jpg|jpeg|gif|png|webp|svg|avif)$ {

  expires 1y;

  add_header Cache-Control “public, max-age=31536000”;

 }

 “`

 

  Using a CDN

 Content Delivery Networks (CDNs) serve images from geographically closest servers and leverage built-in optimization capabilities. This reduces load times and bandwidth usage, providing a better user experience globally.

Continuous Performance Monitoring and Testing

  Google Lighthouse

 Monitor key metrics like LCP and CLS using Google Lighthouse. It provides insights and recommendations to improve web performance.

 

 “`bash

 npm install -g @lhci/cli

 lhci autorun

 “`

 

  WebPageTest

 Perform performance tests directly from your pipeline with WebPageTest. Integration helps in continuous monitoring and improvement.

 

 “`bash

 curl -X POST “https://www.webpagetest.org/runtest.php?url=http://www.example.com&k=YOUR_API_KEY”

 “`

 

  JavaScript Size Check Script

 Identify heavy images that are not optimized or correctly served using a JavaScript size check script.

 

 “`javascript

 <script>

   (function() {

  const SIZE_THRESHOLD = 100  1024; // 100 KB

 

  async function getImageSize(url) {

    try {

      const response = await fetch(url, { method: ‘HEAD’ });

      const size = response.headers.get(‘content-length’);

      return parseInt(size, 10);

    } catch (error) {

      console.error(`Error fetching image size for ${url}:`, error);

      return 0;

    }

  }

 

  async function checkImages() {

    const images = document.querySelectorAll(‘img’);

    for (let img of images) {

      const size = await getImageSize(img.src);

      if (size > SIZE_THRESHOLD) {

        console.warn(`Image ${img.src} exceeds the size threshold (${(size / 1024).toFixed(2)} KB)`);

      }

    }

  }

 

  window.addEventListener(‘load’, checkImages);

   })();

 </script>

 “`

Conclusion

 By implementing these best practices, you can significantly improve the loading times, SEO rankings, and overall user experience of your website. Ensure continuous monitoring and optimization to maintain high performance.

 

  Best Practices Checklist

 

  1. Choose the right image format based on the use case.
  2. Optimize images using lossless or lossy compression.
  3. Use `<picture>` element and `srcset` attribute to serve responsive images.
  4. Leverage CSS tricks to preserve page layout.
  5. Lazy-load non-LCP images.
  6. Use HTTP/2 or HTTP/3 for parallel downloads.
  7. Set appropriate cache-control headers.
  8. Use CDNs for faster image delivery and optimizations.
  9. Integrate performance monitoring into your CI and automate quality checks.

TABLE OF CONTENTS

Contact Info

Please leave your contact info and we will contact you back

    YOUR INFO:

    PROJECT OVERVIEW:

    CRITERIA:

    ADDITIONAL INFO: