Image file size is often the largest contributor to slow page loads. AVIF and WebP formats compress images 25–35% smaller than JPEG and PNG while maintaining visual quality. The catch: older browsers do not support these formats. You need a fallback strategy to serve the right format to each visitor without breaking layouts or loading multiple files.
This post covers How to Write HTML and CSS that automatically detect browser support and load the optimal format. You will not need JavaScript frameworks or external libraries for basic implementation.
Why AVIF and WebP Matter
File size directly affects Page Speed. Smaller images load faster, reducing cumulative layout shift and improving Core Web Vitals. AVIF compresses 30–40% smaller than JPEG. WebP compresses 25–35% smaller. Both formats support transparency, animation, and lossless compression like PNG and GIF.
Browsers adopted these formats at different times. Chrome and Edge support both AVIF and WebP. Firefox added AVIF support in version 93 and WebP in version 65. Safari added WebP in version 14 and AVIF in version 16. Older versions of Internet Explorer and some mobile browsers do not support either format. Fallbacks ensure these visitors still see your images.
The Picture Element Pattern
The HTML <picture> element lets you specify multiple image sources. Browsers load the first source they support and ignore the rest. This is the standard approach for modern responsive images.
Basic structure:
- Wrap your image in a
<picture>tag. - Add
<source>tags for each format, ordered from newest to oldest. - Include a fallback
<img>tag with JPEG or PNG.
Here is a working example:
<picture>
<source srcset="image.avif" type="image/avif">
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="Product photo">
</picture>
The browser reads the <source> tags in order. If it recognizes type="image/avif", it loads image.avif and stops. If not, it checks the next source. If it does not support any source type, it falls back to the <img> tag with image.jpg.
Responsive Images with Multiple Sizes
Use srcset and sizes attributes to serve different image dimensions based on viewport width or device pixel ratio. This prevents loading a 2000-pixel image on a mobile phone.
Add the sizes attribute to tell the browser which image width to load:
<picture>
<source
srcset="image-small.avif 640w, image-large.avif 1280w"
sizes="(max-width: 768px) 100vw, 50vw"
type="image/avif">
<source
srcset="image-small.webp 640w, image-large.webp 1280w"
sizes="(max-width: 768px) 100vw, 50vw"
type="image/webp">
<img src="image-large.jpg" alt="Product photo">
</picture>
The sizes attribute says: "On screens up to 768px wide, load an image 100% of the viewport width. On larger screens, load an image 50% of the viewport width." The browser then picks the smallest image from srcset that matches this rule. On a 375px mobile phone, it loads image-small.avif. On a 1920px desktop, it loads image-large.avif.
Omit the sizes attribute only if your image has a fixed width in CSS. For flexible layouts, always include sizes to avoid over-fetching large files.
CSS Background Images and the @supports Rule
The <picture> element works for HTML <img> tags. For CSS background images, use the @supports rule to detect format support and load the right file.
@supports (background-image: url('data:image/avif;base64,')) checks if the browser understands AVIF. If true, load the AVIF file. If false, fall back to WebP or JPEG:
.hero {
background-image: url('hero.jpg');
}
@supports (background-image: url('data:image/webp;base64,')) {
.hero {
background-image: url('hero.webp');
}
}
@supports (background-image: url('data:image/avif;base64,')) {
.hero {
background-image: url('hero.avif');
}
}
Order matters. Write the JPEG rule first (fallback), then WebP, then AVIF. If the browser supports AVIF, the last rule wins and overrides the others. If it does not support AVIF but supports WebP, the WebP rule applies. If neither is supported, the original JPEG rule applies.
Generating AVIF and WebP Files
You need to create AVIF and WebP versions of your images before writing the HTML. Use a command-line tool or online converter.
FFmpeg is free and widely available. Convert a JPEG to WebP:
ffmpeg -i image.jpg -c:v libwebp -quality 80 image.webp
Convert to AVIF:
ffmpeg -i image.jpg -c:v libaom-av1 -crf 30 image.avif
The -quality and -crf values control compression. Lower numbers mean higher quality but larger file size. Start at quality 80 for WebP and crf 30 for AVIF, then adjust based on visual inspection.
ImageMagick is another option. Install it, then run:
convert image.jpg -quality 80 image.webp
If you host many images, use a build tool like Gulp or Webpack to batch-convert during your build process. This avoids manual conversion and keeps formats in sync with source images.
Online converters (Cloudinary, ImageOptim, TinyPNG) also support batch upload and format conversion. They are convenient for small batches but less practical for hundreds of images.
Fallback Behavior and Browser Support
Test your fallback logic in real browsers. Chrome and Edge load AVIF or WebP instantly. Safari 14–15 skip AVIF and load WebP. Safari 16+ load AVIF. Firefox loads WebP or AVIF depending on version. Internet Explorer 11 and older Android browsers load the JPEG fallback.
Open DevTools (F12 in Chrome). Go to the Network tab. Reload the page. Look at the image request. Check the filename and file size. If you see image.avif, the browser supports AVIF. If you see image.webp, it supports WebP but not AVIF. If you see image.jpg, neither is supported.
Test on actual devices or use Chrome DevTools to emulate older browsers. Click the three-dot menu, select "More tools" → "Network conditions." Uncheck "Use browser default" under User agent and pick an older browser from the dropdown. Reload. The fallback image should load.
Common Mistakes to Avoid
Forgetting the type attribute on <source> tags causes browsers to download and parse the file before checking support. Always include type="image/avif" or type="image/webp". This tells the browser to skip unsupported formats without fetching them.
Listing formats in the wrong order wastes bandwidth. Always order sources from newest to oldest (AVIF, then WebP, then JPEG fallback). If you reverse the order, browsers that support AVIF will load WebP instead and miss the smaller file.
Omitting the sizes attribute on responsive images causes the browser to load the largest image in srcset regardless of screen size. This defeats the purpose of responsive images. Include sizes whenever your image width changes based on viewport or layout.
Using AVIF or WebP for critical above-the-fold images without testing fallback performance first risks broken layouts in unsupported browsers. Always test the fallback chain before deploying to production.
Generating low-quality AVIF or WebP files saves space but damages visual quality. Start with quality 80 (WebP) or crf 30 (AVIF) and only lower if the image still looks acceptable at smaller sizes. Compression artifacts on product photos or hero images hurt user perception more than file size savings help performance.
When to Use Each Format
Use AVIF for all new images where you control the source. It offers the best compression and is now supported in all modern browsers. Older browser fallbacks ensure compatibility.
Use WebP as a secondary format when AVIF support was not yet universal in your audience. If your analytics show 95%+ of visitors use Chrome, Edge, Firefox, or Safari 14+, WebP fallback alone is sufficient. If you serve older Android or Internet Explorer users, keep JPEG as a final fallback.
Keep JPEG or PNG for final fallback. Do not rely on AVIF or WebP as the only format. The fallback chain ensures every visitor sees an image, even if their browser is very old.
Performance Impact and Measurement
Switching to AVIF and WebP typically reduces image payload by 30–40%. This improves Largest Contentful Paint (LCP), Cumulative Layout Shift (CLS), and overall page load time. Use Google Lighthouse or WebPageTest to measure before and after.
In Lighthouse, run an audit and check the "Opportunities" section. Look for "Serve images in next-gen formats." If it appears, Lighthouse detected images that could be smaller in AVIF or WebP. The estimated savings shows how many kilobytes you could save.
Test on real 4G mobile networks. Use Chrome DevTools to throttle to "Slow 4G" and reload. Compare load time with JPEG versus AVIF/WebP. On slow networks, the file size difference is noticeable.
Automation and Build Tools
Manual image conversion does not scale. Use build tools to automate format generation.
Sharp (Node.js) is fast and flexible. Install via npm, then create a script that converts all images in a folder:
const sharp = require('sharp');
const fs = require('fs');
const path = require('path');
const imageDir = './images';
fs.readdirSync(imageDir).forEach(file => {
if (!['.jpg', '.png'].includes(path.extname(file).toLowerCase())) return;
const filePath = path.join(imageDir, file);
sharp(filePath).webp({ quality: 80 }).toFile(filePath.replace(/\.\w+$/, '.webp'));
sharp(filePath).avif({ quality: 60 }).toFile(filePath.replace(/\.\w+$/, '.avif'));
});
Webpack and Next.js have built-in image optimization plugins. Next.js <Image> component automatically generates AVIF and WebP versions and serves the optimal format based on browser support. If you use Next.js, this is often the simplest path.
Gulp and Grunt plugins like gulp-imagemin and imagemin-webp integrate format conversion into your build pipeline. Run the build once, and all images are converted and ready to deploy.
What to Do Next
Start by converting a handful of images to AVIF and WebP using FFmpeg or an online tool. Write the <picture> element for one image and test it in Chrome, Firefox, and Safari. Verify that each browser loads the correct format by checking the Network tab. Once you confirm the fallback chain works, apply the pattern to all images on your site. If you manage many images, set up a build tool to automate conversion and keep formats in sync with source files.
FAQs
Do I have to generate AVIF and WebP for every image?
Yes, if you want to serve the optimal format to each browser. You can start with just WebP for faster adoption, but AVIF offers better compression. Automate the process with a build tool to avoid manual work.
What if my image is already optimized as JPEG?
AVIF and WebP compress further. Even a well-optimized JPEG at quality 85 will be 25–35% smaller as AVIF or WebP. Re-compressing is worth the effort, especially for images above 100 KB.
Can I use AVIF without a WebP fallback?
Not safely. Safari 15 and older Android browsers do not support AVIF. Always include a WebP or JPEG fallback to ensure every visitor sees an image.
Does the @supports rule work for all CSS properties?
Yes, @supports detects any CSS property or value. You can use it for background images, gradients, fonts, and more. However, for images, the <picture> element is simpler and more reliable.
People Also Ask
How do I check if my browser supports AVIF?
Open DevTools (F12) and go to the Network tab. Reload a page with a <picture> element. Look at the image filename. If it ends in .avif, your browser supports AVIF. If it ends in .webp, you support WebP but not AVIF. If it ends in .jpg or .png, you support neither.
Does AVIF work on older Android phones?
Android 12 and newer support AVIF. Older versions do not. Always include a WebP and JPEG fallback for Android users on versions 11 and earlier.
Can I use AVIF for animated images like GIFs?
Yes, AVIF supports animation and compresses animated sequences 50–60% smaller than GIF or animated WebP. Use the same <picture> pattern. Browsers that support AVIF will load the animated AVIF file.
What quality setting should I use for AVIF and WebP?
Start with quality 80 for WebP and crf 30 for AVIF. Lower numbers increase compression but reduce quality. Test visually on product photos and hero images. If the image looks acceptable at smaller sizes, the quality is good enough.
Do I need JavaScript to detect format support?
No. The <picture> element and @supports rule handle detection natively. JavaScript is not required for basic implementation. Use JavaScript only if you need to detect support for other purposes (like choosing a video codec).
How much faster will my site be with AVIF and WebP?
File size typically drops 30–40%, which translates to 1–3 second faster load time on 4G networks depending on image count. Larger improvements appear on sites with many high-resolution images.
Can I use AVIF for email?
No. Email clients have inconsistent format support. Stick to JPEG and PNG for email to ensure compatibility across Gmail, Outlook, Apple Mail, and others.
Do I need to update my image CDN or hosting?
No, you serve AVIF and WebP files the same way as JPEG. Upload them to your server or CDN alongside JPEG versions. The <picture> element handles the rest.
If this post is wrong, outdated, or you would take a different path
I write from work I have done on real sites. Search products change, and a step that was right when I published can go stale. I can also be wrong about the method.
If you disagree with the approach, the facts, or the outcome, I want the detail. Tell me what is off, what you would do instead, and where you saw it. I use that to correct the post so the next reader is not stuck.
This is not a comment thread. Use Contact me so the note is tied to this post and I can reply.
You are sending feedback for
Implement AVIF and WebP Formats with Responsive Fallbacks
Web Development & Martech
https://hammadshk.com/blog/implement-avif-and-webp-formats-with-responsive-fallbacks