Sub topic 9
Serving AVIF and WebP with a JPEG fallback
This chapter assumes you know the img element, srcset with w descriptors, and sizes. It also assumes you know the common image formats (JPEG, PNG, WebP). The goal is to serve a modern, smaller format to browsers that can decode it, and to keep a JPEG for everyone else.
Why switch formats
Resolution switching changes the size of the file. Format switching changes how the same pixels are encoded. AVIF and WebP usually produce smaller files than JPEG at similar visual quality, so the page transfers fewer bytes.
| Format | Typical strength | Typical weakness |
|---|---|---|
| JPEG | Decoded by every browser and tool | Larger files than newer formats |
| WebP | Smaller than JPEG, supports transparency | Not every old client decodes it |
| AVIF | Often the smallest file | Slower to encode, and some clients cannot decode it |
Browser support changes over time, and you cannot assume what a visitor's browser supports. The picture element lets the browser decide from a list you provide, so you do not need scripts or server-side detection.
The picture element and the type attribute
A picture element wraps zero or more source elements and one required img. The browser reads the source elements from top to bottom. It uses the first one it can use. If none match, it uses the img.
For format switching, each source carries a type attribute. The value is a MIME type, which is a standard label for a file format, such as image/avif. The browser compares that label with the formats it can decode. It skips the source without downloading anything if it does not support the type.
<picture>
<source type="image/avif" srcset="photo.avif">
<source type="image/webp" srcset="photo.webp">
<img src="photo.jpg" width="800" height="600" alt="A lighthouse on a rocky coast at sunset">
</picture>Here is what each browser does with this markup:
- A browser that decodes AVIF picks the first source and downloads
photo.avif. - A browser that decodes WebP but not AVIF skips the first source and downloads
photo.webp. - A browser that decodes neither skips both sources and downloads
photo.jpgfrom theimg. - A browser that does not understand
pictureat all ignores thepictureandsourcetags and renders theimg.
The last case is why the img is required. It is the fallback, and it is also the element that renders on the page. The picture and source elements only influence which URL the img shows.
Order matters
The browser takes the first matching source, not the best one. It does not compare file sizes. You must therefore list sources from the format you most want to serve to the one you least want to serve.
A common order is AVIF, then WebP, then the JPEG in the img. If you reversed the first two sources, every browser that supports both formats would receive WebP, and the AVIF source would never be used.
Why the JPEG stays in the img
You may be tempted to drop the JPEG once most browsers support the newer formats. Keep it for these reasons:
- The
imgis the only element that is required. Apicturewithout animgshows nothing. - Attributes such as
alt,width,height,loading, andclassbelong on theimg. Putting them on asourcehas no effect. - Other tools read the
imgsrc. Examples are some email clients, feed readers, crawlers, and "save image as" menus.
The alt text belongs on the img only. All sources share it, because they are the same picture in different encodings.
Combining format switching with srcset and sizes
Each source can have its own srcset and sizes. That gives you format switching and resolution switching together. The browser first chooses a source by type. Then it chooses a width within that source using the normal selection process from earlier chapters.
<picture>
<source
type="image/avif"
srcset="photo-400.avif 400w, photo-800.avif 800w, photo-1600.avif 1600w"
sizes="(min-width: 60em) 33vw, (min-width: 40em) 50vw, 100vw">
<source
type="image/webp"
srcset="photo-400.webp 400w, photo-800.webp 800w, photo-1600.webp 1600w"
sizes="(min-width: 60em) 33vw, (min-width: 40em) 50vw, 100vw">
<img
src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1600.jpg 1600w"
sizes="(min-width: 60em) 33vw, (min-width: 40em) 50vw, 100vw"
width="1600"
height="1200"
alt="A lighthouse on a rocky coast at sunset">
</picture>Keep these points in mind:
- Each format needs its own full set of widths. The
wdescriptors must match the real pixel width of each file. - Repeat the same
sizesvalue on every source and on theimg. Thesizesvalue describes the layout, which does not depend on the format. - The
imgneeds its ownsrcsetif you want the JPEG fallback to be responsive too. Otherwise a browser that falls back to JPEG always downloadsphoto-800.jpg. - The
widthandheightattributes on theimgset the aspect ratio for the wholepicture. Every format variant must have the same aspect ratio as those values.
Generating the files
You need three formats at each width. ImageMagick 7 can write all three, if it was built with AVIF and WebP support. Check with magick -list format.
for w in 400 800 1600; do
magick photo.jpg -resize "${w}x" -quality 80 "photo-${w}.jpg"
magick photo.jpg -resize "${w}x" -quality 75 "photo-${w}.webp"
magick photo.jpg -resize "${w}x" -quality 50 "photo-${w}.avif"
doneThe -quality numbers are not comparable across formats. A value of 50 in AVIF can look similar to 80 in JPEG. Treat the numbers above as starting points. Compare the output visually and by file size, then adjust.
Common errors
- Wrong MIME type. AVIF is
image/avifand WebP isimage/webp. A typo such asimage/aviorimage/jpgmakes the browser treat the type as unsupported, so it skips the source. Note thatimage/jpgis not the registered type for JPEG. Useimage/jpeg. - Wrong order. Listing WebP before AVIF means AVIF is never chosen.
- Server sends the wrong Content-Type. The
typeattribute only helps the browser decide before downloading. The server should still send the correctContent-Typeheader for each file, or some browsers may refuse to display it. - Missing fallback. An
imgwith asrcthat points to AVIF or WebP breaks in clients that cannot decode it. - Mismatched aspect ratios. If the AVIF is cropped differently from the JPEG, the layout changes depending on the browser. Use
mediafor deliberate crops (the art direction chapter covers this), and keep format variants identical in shape. - Mixed up attributes. Putting
mediaandtypeon the samesourcemeans both must match. That is valid, but a mistake in either one silently skips the source. - Missing
widthandheight. Without them the page can shift as images load. Set them on theimg.
Checking which file was chosen
Open the browser's Network panel and filter by images. You should see one request per picture, for the format and width the browser selected. You can also read the choice from JavaScript:
const img = document.querySelector('picture img');
console.log(img.currentSrc);
console.log(window.devicePixelRatio);currentSrc is a property of the img element, even when the file came from a source. If the output ends in .avif or .webp, format switching worked. If it ends in .jpg in a browser that should support the newer format, check the type value, the source order, and whether the file URLs return a 200 status.
When not to use multiple formats
Serving three formats triples the files to produce, store, and cache. It is worth it for large photographic images, such as hero images and galleries. For small icons, logos, and simple graphics, SVG or a single well-compressed PNG is often simpler. Measure the savings before adding the extra markup to every image on a site.
Exercise
A page uses a picture element with the sources listed in this order: first type="image/webp" with photo.webp, then type="image/avif" with photo.avif, and finally an img with src="photo.jpg". A browser supports both AVIF and WebP. Which file does it download, and what change would make it download the AVIF file?
Show answer
It downloads photo.webp, because the browser uses the first source whose type it supports and does not compare file sizes. To make it download the AVIF file, move the AVIF source above the WebP source.
Exercise
You add alt="A lighthouse" and loading="lazy" to a source element inside a picture, and leave the img without them. Will the attributes take effect? Where should they go?
Show answer
No. Only the img element uses alt and loading, so attributes placed on a source have no effect. Move them to the img element.