Why AVIF and WebP
It should be pretty obvious, but as the web grows, web developers need to do their best to reduce the payload to the browser. AVIF and WebP came along as a new image compression formats to produce similar quality images at a large reduction in file size. Sounds great! Let’s do it.
I started by building the image tag. The first tag is a fallback for browsers that won’t support the
<source> tag. Then, we’ll load two different
<source> tags, letting the browser know that we have AVIF and WebP options as well.
<picture> <img src="image.jpg" /> <source srcset="image.avif" type="image/avif" /> <source srcset="image.webp" type="image/web" /> </picture>
Time to Test
Great. We’ve build the AVIF and WebP images, created the image tag and now we’re good to go. I loaded up DevTools, checked that the WebP URL was loading correctly, then watched the “Network” tab to see the browser load the AVIF and WebP images instead of the optimized images.
It was loading the JPG instead of the optimized images. I don’t care to tell you how long I worked to fix this issue, but it was far too long.
Turns out it was simple. The
<source> tags inside of the
<picture> tag have to be in order. So, you’ll list the most optimized format first, then down to JPG. For example, you’d load AVIF first, then WebP and finally the fallback tag.
<picture> <source srcset="image.avif" type="image/avif" /> <source srcset="image.webp" type="image/web" /> <img src="image.jpg" /> </picture>