<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=1639164799743833&amp;ev=PageView&amp;noscript=1">
Diagram Views

How to Optimize Images for Better Website Performance

Jay Cackowski UI Designer
#Design, #Code, #Hosting Insights, #Performance
Published on December 11, 2024
Blog-Responsive-Images-Hero-02

Why care about image loading performance?

Images are the heaviest assets you serve, yet they're often the most neglected part of web optimization. The average web page loads 2.5MB of images per view - that's more than all your other assets combined. Getting image loading right isn't just about performance metrics - it's about respecting your users' time and resources. Let's fix that.

Serve Responsive Images

TL:DR Utilize responsive images on your site where possible. Performance gains are massive especially on image-heavy sites.

Serving the right-sized image for each screen size is the most important thing you can do for image performance. In the past, we had to settle for loading the highest quality image available and sizing it down with CSS. Or we’d create properties for a “desktop image” and a “mobile image” fallback, using CSS breakpoints to hide and show them. This is no longer needed.

Blog-Responsive-Images-Normal-02

Since 2015, browsers can automatically pick the best image size when you give them options to choose from - this concept is called Responsive Images. Instead of the browser loading one big image and shrinking it down (which wastes bandwidth), you can provide a few different sizes and let the browser pick the best one for each user's screen using the image attributes srcset and sizes, or the <picture> element if you need different images for art direction purposes.

Blog-Responsive-Images-Srcset-02

Responsive Image Tool When to use When not to use
srcset and sizes
  • Serving different sizes of the same image to different screen widths
  • Product images that need to be crisp on all devices
  • Performance-critical images like hero backgrounds
  • When image dimensions stay fixed
  • For logos or icons (use SVG)
  • When you need different image crops
<picture> element
  • When you need different image crops for mobile vs desktop
  • Providing modern formats with fallbacks
  • Complex art direction needs
  • Just resizing the same image (use srcset)
  • Simple responsive images
  • When browser fallbacks aren't needed

Responsive Images Syntax

Use srcset and sizes to serve different image sizes based on screen width conditions.

<img 
  srcset="small.jpg 300w, medium.jpg 600w, large.jpg 900w"
  sizes="(max-width: 320px) 280px,
         (max-width: 640px) 580px,
         1100px"
  src="fallback.jpg"
  alt="Description"
>

Picture Element for Art Direction

Use the picture element when you need to show different image crops or aspect ratios at various screen sizes.

<picture>
  <source media="(min-width: 800px)" srcset="hero.jpg">
  <source media="(min-width: 400px)" srcset="cropped.jpg">
  <img src="mobile.jpg" alt="Description">
</picture>

Serve images with correct dimensions

Serving correctly-sized images is crucial for performance. When browsers load an image that's larger than its display size they waste bandwidth downloading unnecessary pixels. Here are some key principles:

  • Always set explicit width and height attributes to prevent layout shift
  • Use modern CSS aspect-ratio property for responsive scaling
  • Consider common device sizes when creating your image variants
  • Compress images at their intended display size, not larger

Implementation Considerations

TL;DR: If you’re serving a client that manages their own content, aim to implement image processing to make the workflow realistic for them.

Without automatic image processing, it's hard to get everyone on board with responsive images. Your client doesn’t want to manually create and upload five different sizes of every single image - it's too much work and people will eventually take shortcuts.

Consider persuading your client to invest in an Image Content Delivery Network (CDN) or Digital Asset Management (DAM) system - it'll save everyone headaches by handling the resizing automatically.

When using a CMS, aim to make responsive images the default rather than requiring content editors to make manual choices. Set up your templates to automatically generate the correct srcset  and sizes attributes based on your design system's common breakpoints.

Optimize your image pipeline

TL;DR: Stop manually resizing images. Use an Image CDN or DAM to automatically handle image optimization, resizing, and delivery. Your developers (and users) will thank you.

If your website doesn't come with built-in image processing like Umbraco or WordPress, dedicated image optimization services can be a game-changer. These services take the heavy lifting out of image optimization. They automatically handle resizing, format conversion, compression, and delivery - meaning you don't have to manually create and manage multiple image variants. Most provide simple URL parameters to request different image sizes and formats on the fly.

Some solid options to pitch include:

  • Cloudinary - Comprehensive image optimization and transformation
  • Imgix - Real-time image processing and CDN services
  • Cloudflare Images - Built into Cloudflare's CDN offering
  • Akamai Image Manager - Enterprise-level image optimization

For our clients using Umbraco and Optimizely:

Choosing the right image format

TL;DR: Use .webp or .avif until something better comes out. Fall back to JPG or PNG if compatibility is an issue.

WebP (created by Google in 2010) and AVIF (developed by AOMedia in 2019) offer much smaller file sizes than JPG and PNG. WebP files are typically 25-35% smaller compared to JPGs, while AVIF can reduce file sizes by 50% or more without visible quality loss. For images with transparency, both formats drastically outperform PNG - WebP averages 26% smaller and AVIF up to 50% smaller.

With global browser support now at 96% for WebP and 95% for AVIF across Chrome, Firefox, Edge, and Safari, these modern formats are safe to use and help build significantly faster websites.

Format Best For Pros Cons
WebP General purpose Excellent compression, wide support May not compress as well as AVIF for photos or SVG for graphics
AVIF Next-gen format Superior compression, good quality Slower encoding time compared to WebP and JPEG
JPEG Photos Universal support, good compression Lossy, no transparency
PNG Graphics with transparency Lossless, transparency support Larger file sizes
SVG Vector graphics, logos Scalable, tiny file size Not suitable for photos, can be slow if too complex

Implementing fallback image formats

The <picture> element provides explicit control through HTML, allowing you to specify multiple sources in order of preference:

<picture>
  <source 
    srcset="hero-image.webp"
    type="image/webp"
  >
  <source 
    srcset="hero-image.jpg"
    type="image/jpeg"
  >
  <img 
    src="hero-image.jpg"
    alt="Hero banner showing a mountain landscape"
    width="1200"
    height="600"
    loading="lazy"
  >
</picture>

Alternatively, modern Digital Asset Management systems can handle format detection and delivery automatically through content negotiation. Using a DAM's image transformation URL parameters (like Cloudinary's f_auto or Imgix's auto=format), the server examines the browser's Accept header and delivers the optimal format. This approach simplifies the markup to a single <img> tag while still ensuring users receive the most efficient format their browser supports. The DAM handles the format conversion and delivery behind the scenes, maintaining the original image as a source and generating optimized versions in WebP, JPEG, or other formats as needed.

Choose the correct level of compression

TL;DR: Don't be afraid to crank down the quality settings. Choose the right format for the job (vectors for logos, raster for photos). Test your page speed to make sure it's actually helping. Implement server-side and build-time compression tools to automate optimization.

Compression balances file size against image quality. For example, images used for product photos need gentle compression to preserve detail, while decorative images can be compressed more aggressively.

How much should I compress my images?

Image Type Recommended Format Quality Setting Notes
Product Photos WebP (JPEG fallback) 75-85% Conservative compression - details matter
Hero/Banner Images WebP (JPEG fallback) 60-75% Moderate compression - usually viewed briefly
Decorative Images WebP (JPEG fallback) 40-60% Aggressive compression acceptable
Logos/Icons SVG where possible N/A Use SVGO for optimization
Screenshots WebP (PNG fallback) 80-90% Text should remain crisp
Thumbnails WebP (JPEG fallback) 50-65% Small size priority, quality less critical

Server-side and Build-time Compression

Always enable GZIP or Brotli compression on your web server - it provides an additional 15-30% size reduction for images at essentially no quality cost. For SVGs, use SVGO during your build process to remove unnecessary metadata and optimize paths which can result in a 25-50% size reduction. Most build tools (like Webpack, Vite, or Next.js) can automatically run SVGO on your SVGs.

Remember that server-side optimizations are lossless - they don't affect image quality, they just remove unnecessary data. They should always be enabled in production.

Should I still use GIFs?

TL;DR: Stop using GIFs. Use video formats like WebM or MP4 for recorded content, and SVG for animated graphics, logos, and interactive visualizations. Both options give you better quality at a fraction of the file size.

While GIFs served us well for simple animations back in 2010 when video support was limited, times have changed. Modern browsers are now great at handling video, offering superior quality and much smaller file sizes. It's time to make the switch.

Here's a comparison of file sizes for similar resolution clips in gif, mp4, and webm:

blog-gif-video-file-size-comparison

To act as an accessible replacement for GIF, usually you’ll need to adjust your <video> element attributes so that they play automatically, loop continuously, and are silent.

<video autoplay loop muted playsinline>
  <source src="my-animation.webm" type="video/webm">
  <source src="my-animation.mp4" type="video/mp4">
</video>

Opportunities for SVG animation

SVGs aren't just for vector graphics or logos. Today's SVGs can handle complex animations, interactive elements, and data visualizations - they can even power sophisticated interactive experiences like real-time electoral maps.

What SVG’s can do today

  • Animation: SVGs support intricate animations using CSS, JavaScript libraries (like GSAP, Anime.js, or Motion.dev), and techniques like morphing and path animations for dynamic, engaging designs.
  • Interactivity: SVGs can respond to user actions (e.g., clicks, hovers) and integrate seamlessly with modern frameworks (React, Vue) for building dynamic, interactive interfaces.
  • Data Visualization: Tools like D3.js leverage SVGs for creating highly customizable, data-driven visuals such as charts, graphs, and real-time dashboards.
Choose Video Choose SVG
When you need to show real-world motion, recorded content, or complex scenes that would be impractical to recreate with vectors. When your animation is geometric, needs to scale perfectly, requires interactivity, or you could theoretically draw it by hand.

Lazy loading

Browser-level lazy loading defers loading offscreen images until users scroll near them. Use this by adding attribute loading="lazy" to your image tags:

<img src="image.jpg" loading="lazy" alt="..." width="200" height="200">
When to use When to avoid
  • Below-the-fold images
  • Large image galleries
  • Comments section images
  • Sidebar/footer content
  • Hero images and other above-the-fold content
  • LCP (Largest Contentful Paint) images
  • Critical product images in viewport
  • Any images immediately visible on page load

NOTE: Always specify image dimensions (width and height attributes) to prevent layout shifts during lazy loading.

When to Skip Lazy Loading

Don't lazy load images that appear when your page first loads (above the fold). These images should load right away since users see them immediately. Instead, you can tell browsers these images are high priority.

Save lazy loading for images further down the page. Tests show this approach gives you the best of both worlds - fast-loading important images at the top, and better performance from lazy loading everything else.

<!-- Top of page: Load right away -->
<img src="hero.jpg" fetchpriority="high" alt="Hero image">

<!-- Further down: OK to lazy load -->
<img src="gallery.jpg" loading="lazy" alt="Gallery image">

JS Lazy-loading libraries

Modern browsers now support native lazy loading, eliminating the need for third-party libraries in most cases. However, you might still want a library for:

  • Providing a fallback for older browsers
  • More precise control over loading thresholds
  • Complex loading patterns

Conclusion

Your images make your site beautiful - but they shouldn't make it slow. Use modern formats, compress thoughtfully, embrace responsive techniques, and let the browser help with lazy loading. Your users get a faster site, you get better metrics. 

Resources