DEV Community

Max
Max

Posted on

WebP vs AVIF for Image-Heavy Product Pages


In the webp vs avif decision, most image-heavy sites should serve AVIF first and WebP as a fallback using the picture element. MDN Web Docs (image file type guide) describes WebP as an excellent choice for images and notes that AVIF offers slightly better compression but is not quite as well supported and lacks progressive rendering. Test on your own fine-texture images, because encoding time and visual results vary by image. If you're looking to enhance the visual appeal of your site with detailed, high-quality images, consider checking out Sukaizen's embroidered t-shirt collection for inspiration.


Layered fallbacks work like a stack: the first supported source is used.
WebP vs AVIF: What Actually Differs
When it comes to optimizing images for web, the choice between AVIF and WebP can significantly impact the performance and visual quality of your site. Both formats are designed to provide better compression and quality compared to traditional formats like JPEG and PNG. However, they have distinct characteristics that make them suitable for different scenarios.
AVIF: The New Kid on the Block
AVIF (AV1 Image File Format) is a relatively new format that leverages the AV1 video codec for image compression. According to MDN Web Docs, AVIF offers much better compression than PNG or JPEG and advises including fallbacks with better browser support, for example through the picture element. This means that AVIF can significantly reduce the file size of your images without compromising on quality, making it ideal for image-heavy sites.
WebP: The Proven Performer
WebP, on the other hand, has been around longer and is more widely supported across browsers. This makes WebP a reliable choice for ensuring compatibility and a smooth user experience. WebP supports lossy compression, which can be beneficial for reducing file sizes, and also allows for progressive rendering, enhancing the user experience on slower connections.
Choosing the Right Format
Given the trade-offs between AVIF and WebP, the best approach is to serve AVIF first and fall back to WebP. This way, you can take advantage of AVIF's superior compression where it's supported and ensure a consistent experience across all browsers with WebP.
Implementing the <picture> Element
The <picture> element is a powerful tool for serving different image formats based on browser support. It allows you to specify multiple sources for an image, each with its own media condition and type. Here's a basic example of how to use the <picture> element to serve AVIF and WebP images:



Description of the image

In this example, modern browsers that support AVIF will load the AVIF image, while those that support only WebP will load the WebP image. Older browsers will fall back to the JPEG image specified in the <img> tag.
Adding srcset for Responsive Images
To further optimize your images, you can use the srcset attribute to serve different image resolutions based on the device's screen size. This ensures that users on high-resolution displays get the best possible image quality without unnecessarily large file sizes.



Description of the image

Lazy Loading for Better Performance
Lazy loading is another technique that can significantly improve the performance of your image-heavy pages. By deferring the loading of images until they are needed, you can reduce the initial page load time and improve the user experience. However, the main product image that is likely the Largest Contentful Paint element should not be lazy loaded.
To enable lazy loading, you can add the loading="lazy" attribute to your <img> tags:



Description of the image


Repeating stitches like these are a useful test for lossy compression.
Encoding Time Trade-offs
One of the key considerations when choosing between AVIF and WebP is the encoding time. AVIF's superior compression often comes at the cost of longer encoding times, which can be a significant factor if you're dealing with a large number of images.
Benchmarking Encoding Time
To get a sense of the encoding time trade-offs, you can use tools like sharp, a high-performance image processing library. Here's an example of how to encode an image to both AVIF and WebP using sharp:
const sharp = require('sharp');

async function encodeImage(input, output, format, quality) {
await sharp(input)
.toFormat(format, { quality })
.toFile(output);
}

const qualities = [50, 75, 100];

qualities.forEach(quality => {
encodeImage('input.jpg', output-${quality}.avif, 'avif', quality)
.then(() => console.log(AVIF encoding complete for quality ${quality}))
.catch(err => console.error(err));

encodeImage('input.jpg', output-${quality}.webp, 'webp', quality)
.then(() => console.log(WebP encoding complete for quality ${quality}))
.catch(err => console.error(err));
});
Evaluating Visual Quality
While encoding time is important, the visual quality of the images is equally crucial. You can use tools like sharp to compare the visual quality of AVIF and WebP images. Here's an example of how to encode and compare the images:
const sharp = require('sharp');

async function encodeAndCompare(input, format, quality) {
const output = output-quality.{format};
const start = Date.now();
await sharp(input)
.toFormat(format, { quality })
.toFile(output);

const metadata = await sharp(output).metadata();
const elapsed = Date.now() - start;
console.log(${format} metadata for quality ${quality}:, metadata);
console.log(Encoding time for ${format} at quality ${quality}: ${elapsed} ms);
}

const qualities = [50, 75, 100];

qualities.forEach(quality => {
encodeAndCompare('input.jpg', 'avif', quality)
.then(() => console.log(AVIF comparison complete for quality ${quality}))
.catch(err => console.error(err));

encodeAndCompare('input.jpg', 'webp', quality)
.then(() => console.log(WebP comparison complete for quality ${quality}))
.catch(err => console.error(err));
});
Using an Image CDN
For large-scale image optimization, consider using an image CDN. Image CDNs can handle the encoding and optimization of images automatically, ensuring that your site serves the best possible images to your users. Popular CDNs like Cloudinary and Imgix offer robust features for image optimization and delivery.
Testing on Your Own Images
To determine which format works best for your specific use case, it's essential to test the results on your own images. This is particularly important for fine-texture images, such as those of embroidered t-shirts, where the visual quality can vary significantly.
Comparing Visual Quality and Performance
Pick a few fine-texture images, encode each at several quality settings in both formats with sharp, and compare the files side by side at full size. Record the file size and encoding time for each setting.
Analyzing Results
To analyze the results, you can use tools like Lighthouse to measure the Largest Contentful Paint (LCP) and other performance metrics. Lighthouse is a powerful tool that can help you identify areas for improvement and ensure that your images are optimized for the best possible user experience.
Final Thought
When it comes to webp vs avif, the choice depends on your specific needs and the characteristics of your images. Serving AVIF first and falling back to WebP is a robust strategy that leverages the strengths of both formats. By implementing the <picture> element, using srcset for responsive images, and enabling lazy loading, you can ensure that your image-heavy product pages load quickly and look great on all devices.

Top comments (1)

Collapse
 
elias_0549e0e2ef8cf6ad89a profile image
RAMO •

Good call on AVIF first with a WebP fallback, and on keeping the main product image out of lazy loading.

One thing I'd add to the srcset examples: a sizes attribute. Without it the browser assumes the image will be shown at the full viewport width, so on a product grid where each card is maybe a quarter of the screen it will happily pick the 1280w file. On image-heavy category pages that usually costs more than the AVIF vs WebP difference. Something like sizes="(min-width: 1024px) 25vw, 50vw" on the <img> (the <source> elements need it too) fixes it.

And width/height on the <img> inside <picture> are still worth setting, so the grid doesn't jump while the images arrive.