Frontend Patterns

Pattern

Image Optimization

Compressing, resizing, and serving images in modern formats to reduce bandwidth usage.

Performance Advanced

Image Optimization

Problem

Unoptimized images account for megabytes of page weight, dominating load times on slow connections. Designers export full-resolution PNGs that are 10x larger than necessary. Mobile users download desktop-sized images, wasting bandwidth and battery. Pages visually load but remain sluggish while massive hero images trickle in.

Solution

Compress, resize, and serve images in modern formats appropriate for device and viewport. This dramatically reduces bytes transferred and improves load times, especially on mobile.

Example

This example demonstrates responsive images with modern format (WebP), multiple sizes for different viewports, and lazy loading.

<img
  src="/images/hero.webp"
  <!-- Provide multiple image sizes for different screen widths -->
  srcset="/images/hero-400.webp 400w, /images/hero-800.webp 800w"
  <!-- Tell browser which size to use based on viewport -->
  sizes="(max-width: 600px) 400px, 800px"
  alt="Hero image"
  <!-- Defer loading until image is near viewport -->
  loading="lazy"
/>

Benefits

  • Dramatically reduces page weight by compressing images without visible quality loss.
  • Improves load times especially on mobile by serving appropriately sized images.
  • Reduces bandwidth costs by transferring fewer bytes per page load.
  • Supports modern formats like WebP and AVIF for better compression ratios.

Tradeoffs

  • Requires build-time processing or server-side infrastructure to generate image variants.
  • Adds complexity with srcset and sizes attributes that can be difficult to get right.
  • May need fallback formats for older browsers that don’t support modern image types.
  • Storage costs increase when maintaining multiple versions of each image.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.