Step 8: Responsive Images with srcset

The Solution

Using srcset and sizes attributes allows browsers to download the most appropriate image size based on the device's characteristics.

Benefits:

  • Appropriate image sizes for different devices
  • Reduced bandwidth usage
  • Faster page loads
  • Better user experience

Fixed Code:


<picture>
  <source
    media="(min-width: 1024px)"
    srcset="large.jpg"
  >
  <source
    media="(min-width: 768px)"
    srcset="medium.jpg"
  >
  <img
    ngSrc="small.jpg"
    width="400"
    height="300"
    alt="Responsive image"
  >
<picture>
          

Resize your browser window and check the Network tab. Different image sizes will be downloaded based on your viewport width. Here is more information about the best practices for responsive images: https://dev.to/activenode/srcset-sizes-picture-media-what-you-might-not-have-known-31nf

Responsive image

This image adapts its size based on the viewport width:

  • Desktop (≥1024px): 1080x720
  • Tablet (≥768px): 720x480
  • Mobile: 400x300
Card image 1

Card 1

Card image 2

Card 2

Card image 3

Card 3

Card image 4

Card 4

Build-time Optimization

  • Automatic format conversion
  • Multiple sizes generation
  • Optimized compression
  • Cache-friendly filenames

Format Support

  • AVIF for best compression
  • WebP for wide support
  • JPEG/PNG fallback
  • Automatic format selection

Performance Benefits

  • Reduced bandwidth usage
  • Faster page loads
  • Better Core Web Vitals
  • Improved user experience