Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to use WebP and AVIF images with a fallback

Short answer

Wrap <img> in <picture> and list the formats from the best to the simplest:

<picture>
  <source srcset="photo.avif" type="image/avif">
  <source srcset="photo.webp" type="image/webp">
  <img src="photo.jpg" alt="A flower" width="800" height="500">
</picture>

The browser reads type, skips the formats it does not understand and downloads only one file — the first one that fits. If none fits, the JPEG from <img> is used.

There is no live example here: the site only has JPEG images, and with them you would see no difference — <picture> would simply show the fallback file.

Why bother

At the same quality WebP is usually 25–35% smaller than JPEG, and AVIF is smaller still, sometimes by half. For a page full of photos that means seconds of loading on a slow connection. Today every modern browser understands both formats, and <picture> covers the old ones.

Together with different sizes

<source> also has srcset and sizes, so the format and the width can be chosen at the same time:

<picture>
  <source type="image/avif" srcset="photo-400.avif 400w, photo-800.avif 800w" sizes="(max-width: 600px) 100vw, 600px">
  <img src="photo-800.jpg" srcset="photo-400.jpg 400w, photo-800.jpg 800w" sizes="(max-width: 600px) 100vw, 600px" alt="A flower" width="800" height="500">
</picture>

How to get the files

You can convert an image in the free online tool Squoosh or with commands:

cwebp -q 80 photo.jpg -o photo.webp
avifenc photo.jpg photo.avif

Common mistake

Putting WebP before AVIF or forgetting the type attribute. The browser takes the first matching <source>, so AVIF after WebP will almost never be chosen. And without type the browser does not know the format in advance and may pick a file it cannot display.

Functions used in this recipe

  • <picture> — A container for several versions of an image: the browser picks a matching `<source>` or falls back to `<img>`.
  • <source> — One of the file versions for `<video>`, `<audio>` or `<picture>`.
  • <img> — An image.
  • srcset — Several files of one image in different sizes: the browser picks the one that fits the screen.

Thanks for reading!

Donate to the site — we work hard for you.