Image Optimization Cheatsheet

Effective image optimization is a cornerstone of high-performance web applications and efficient content delivery. Large, unoptimized images are…

Effective image optimization is a cornerstone of high-performance web applications and efficient content delivery. Large, unoptimized images are frequently the primary culprits behind slow page load times, increased bandwidth consumption, and a degraded user experience. This guide details practical strategies, tools, and technical specifications for optimizing images across various deployment scenarios, from static sites to dynamic web platforms.

Choosing the Right Image Format

The selection of an appropriate image format is foundational to optimization. Different formats excel in different use cases, offering trade-offs between compression efficiency, feature support (e.g., transparency, animation), and browser compatibility.

Raster Formats

  • JPEG (.jpg, .jpeg): Ideal for photographs and images with complex color gradients. It uses lossy compression, which discards some image data to achieve smaller file sizes. Quality settings range from 0-100, with 80-85 often providing a good balance for web use.
  • PNG (.png): Best for images requiring transparency (alpha channel) or sharp-edged graphics like logos, icons, and text. PNG supports lossless compression, meaning no image data is lost, resulting in larger file sizes than JPEGs for photographic content. PNG-8 (256 colors) is suitable for simple graphics, while PNG-24 (true color) handles more complex images.
  • GIF (.gif): Primarily used for simple animations and images with a very limited color palette (256 colors). Its compression is lossless but less efficient than PNG for static images. Avoid for photos.
  • WebP (.webp): A modern format developed by Google, offering superior lossy and lossless compression for photographic and graphic images, respectively. It generally provides 25-35% smaller file sizes than JPEG or PNG at comparable quality. Widely supported in modern browsers (Chrome, Firefox, Edge, Safari 14+).
  • AVIF (.avif): The newest open-source image format based on the AV1 video codec. AVIF offers even better compression than WebP, often achieving 30-50% smaller files than JPEG. It supports lossy and lossless compression, transparency, and HDR. Browser support is growing rapidly (Chrome 85+, Firefox 93+, Safari 16.4+).

Vector Formats

  • SVG (.svg): Scalable Vector Graphics are XML-based, resolution-independent images. Perfect for logos, icons, and illustrations that need to scale without pixelation across various devices and screen densities. They are typically very small in file size and can be manipulated with CSS and JavaScript.

Recommendation: Prioritize modern formats like AVIF and WebP using the <picture> element, falling back to JPEG or PNG for older browser compatibility.

Responsive Images with <picture> and srcset

Delivering appropriately sized images is crucial. Sending a 4K image to a mobile device wastes bandwidth and processing power. Responsive images allow browsers to select the most suitable image based on viewport dimensions, device pixel ratio (DPR), and supported formats.

<picture>
  <source srcset="hero.avif?w=400 400w, hero.avif?w=800 800w, hero.avif?w=1200 1200w"
          sizes="(max-width: 600px) 100vw, (max-width: 1200px) 50vw, 1200px"
          type="image/avif">
  <source srcset="hero.webp?w=400 400w, hero.webp?w=800 800w, hero.webp?w=1200 1200w"
          sizes="(max-width: 600px) 100vw, (max-width: 1200px) 50vw, 1200px"
          type="image/webp">
  <img src="hero.jpg?w=800"
       alt="Description of the hero image"
       loading="lazy"
       width="1200"
       height="675">
</picture>
  • <picture>: A container element for multiple <source> elements and one <img> element. It enables conditional loading based on media queries (e.g., screen size) or image format support.
  • <source>: Specifies different image resources.
    • srcset: A comma-separated list of image URLs and their intrinsic widths (e.g., image-400w.jpg 400w) or pixel densities (e.g., image-x1.5.jpg 1.5x). The browser chooses the best fit.
    • sizes: Describes how the image will be displayed on the page relative to the viewport. For example, (max-width: 600px) 100vw, 50vw tells the browser that for viewports up to 600px wide, the image will take up 100% of the viewport width; otherwise, it will take up 50%. This helps the browser calculate the optimal image size to request from srcset.
    • type: Specifies the MIME type of the image, allowing browsers to skip unsupported formats and move to the next <source> or the <img> fallback.
  • <img>: The fallback element. It must always be present.
    • src: The default image URL.
    • loading="lazy": Defers loading of images outside the viewport until the user scrolls near them, improving initial page load time. Note: For images in the initial viewport, use loading="eager" or omit the attribute.
    • width and height: Explicitly setting these attributes helps prevent Cumulative Layout Shift (CLS) by reserving the necessary space before the image loads.
    • alt: Essential for accessibility and SEO. Describes the image content for screen readers and when images fail to load.

Image Compression Techniques

Beyond format selection, compression is critical. It involves reducing file size without perceptible loss of quality.

Lossy Compression

Removes some image data to achieve smaller file sizes. Ideal for photographs. The key is finding the right balance:

  • JPEG: Tools like jpegoptim, mozjpeg (for better quality at low bitrates), or online services like TinyPNG (which also handles PNGs) can significantly reduce JPEG sizes. A quality setting of 75-85 is often a good starting point.
  • WebP/AVIF: These formats have built-in superior lossy compression algorithms. When converting, ensure you configure the quality settings appropriately. For example, using cwebp -q 75 input.jpg -o output.webp.

Lossless Compression

Reduces file size without discarding any data, preserving perfect image quality. Best for graphics, logos, and images with text:

  • PNG: Tools like optipng, pngcrush, or online services like TinyPNG strip unnecessary metadata, optimize palette, and apply more efficient compression algorithms.
  • SVG: SVGs are often verbose. Tools like SVGO can remove unnecessary elements, comments, and optimize paths, drastically reducing file size.

Tools for Compression:

  • CLI Tools:
    • ImageMagick (cross-platform): A powerful suite for creating, editing, composing, or converting bitmap images. Can handle various formats and operations. Example: convert input.jpg -strip -quality 80 output.jpg
    • cwebp (WebP encoder): cwebp -q 80 input.jpg -o output.webp
    • avifenc (AVIF encoder, from libavif): avifenc --min 0 --max 63 -d 8 -a end-usage=q -a cq-level=23 input.png output.avif (adjust cq-level for quality)
    • jpegoptim: jpegoptim --strip-all --max=80 input.jpg
    • optipng: optipng -o7 input.png (-o7 is aggressive optimization)
    • SVGO (Node.js-based): svgo input.svg -o output.svg
  • Online Services: TinyPNG, Compressor.io, Squoosh.app (Google's web app for format conversion and compression).
  • CDNs with Image Optimization: Cloudflare Images, Cloudinary, Imgix, Akamai Image Manager. These services can automate format conversion, resizing, and compression on-the-fly.

Content Delivery Networks (CDNs) and Caching

CDNs are essential for delivering images quickly to users worldwide. They cache image assets at edge locations geographically closer to users, reducing latency and offloading traffic from origin servers.

  • Edge Caching: Images are stored on CDN servers. Subsequent requests for the same image are served directly from the CDN.
  • Image Transformation Services: Many CDNs (e.g., Cloudflare Images, Cloudinary) offer on-the-fly image optimization. You upload a single high-resolution image, and the CDN generates optimized versions (different sizes, formats, qualities) dynamically based on request parameters (e.g., example.com/image.jpg?w=400&format=webp&quality=75). This significantly simplifies the responsive image workflow.
  • HTTP Caching Headers: Ensure your web server or CDN is configured to send appropriate HTTP caching headers (Cache-Control, Expires, ETag, Last-Modified) to maximize browser caching of images. For static, versioned assets (e.g., image-v2.jpg), a Cache-Control: public, max-age=31536000, immutable header is highly effective.
# Nginx example for image caching
location ~* \.(jpg|jpeg|gif|png|webp|avif|svg|ico)$ {
    expires 365d;
    add_header Cache-Control "public, max-age=31536000, immutable";
    access_log off;
    log_not_found off;
}

Lazy Loading and Prioritization

Not all images need to load immediately. Deferring offscreen images can significantly improve Largest Contentful Paint (LCP) and Time to Interactive (TTI).

  • Native Lazy Loading: As shown earlier, the loading="lazy" attribute on <img> and <iframe> elements is the most straightforward method. It's supported by all major browsers.
  • Intersection Observer API: For more fine-grained control or when supporting older browsers, the Intersection Observer API can be used to implement custom lazy loading logic.
  • Prioritization: Images within the initial viewport ("above the fold") should be loaded with high priority. Avoid lazy-loading these critical images. Consider using <link rel="preload" as="image" href="..."> for the LCP image if it's not immediately present in the HTML due to dynamic rendering.

Common Pitfalls and Troubleshooting

  • Forgetting width and height attributes: Leads to Cumulative Layout Shift (CLS), negatively impacting user experience and SEO. Always specify dimensions.
  • Over-optimizing: Aggressive compression can lead to noticeable quality degradation. Always review images after optimization.
  • Missing alt attributes: Harms accessibility for visually impaired users and reduces SEO benefits.
  • Ignoring browser support for modern formats: Relying solely on WebP or AVIF without <picture> fallbacks will result in broken images for users on older browsers.
  • Not using CDNs for high-traffic sites: Images are often the heaviest assets; local serving can bottleneck your origin server and increase latency.
  • Incorrect sizes attribute: A misconfigured sizes attribute can cause the browser to download an image that is either too large (wasting bandwidth) or too small (appearing blurry). Use browser developer tools (e.g., Chrome's Elements tab > Computed styles for image, or Network tab) to verify the rendered size and the loaded resource.
  • Not clearing CDN cache: After deploying new image versions, ensure CDN caches are invalidated to prevent serving stale content.

Back to the knowledge base · Ask the AI assistant