Serving AVIF Images with JPEG Fallback in HTML
This article details the standard, production-ready markup pattern for delivering high-compression AVIF images to modern browsers while providing an automatic, reliable JPEG fallback for legacy environments. By using native HTML5 markup, you can maximize image compression and page load speeds without breaking compatibility across older devices and platforms.
The Standard Picture Element Pattern
The most reliable, cross-browser method to serve AVIF with a fallback
is the HTML5 <picture> element. The browser evaluates
child <source> tags from top to bottom, selecting the
first format it natively supports, and falls back to the nested
<img> element if no source matches.
<picture>
<source srcset="image.avif" type="image/avif">
<img src="image.jpg" alt="A descriptive description of the image" width="800" height="600" loading="lazy" decoding="async">
</picture>Essential Implementation Details
To ensure the pattern is robust, performant, and accessible, several attributes must be configured correctly:
1. The type Attribute
The type="image/avif" attribute is mandatory on the
<source> tag. Browsers use this MIME type to
determine format support before downloading the file. Without this
attribute, the browser may attempt to download the file before checking
compatibility, defeating the purpose of the fallback.
2. The
<img> Tag as the Presentation Layer
The <picture> wrapper acts solely as a
format-selection mechanism. Styling, dimensions, accessibility, and lazy
loading must all be declared on the inner <img>
element:
- Dimensions (
widthandheight): Always specify explicit pixel dimensions on the<img>tag to preserve the aspect ratio and prevent Cumulative Layout Shift (CLS). - Accessibility (
alt): Place thealttext on the<img>element. Screen readers ignore<source>elements and parse the<img>tag directly. - Loading and Decoding: Use
loading="lazy"to defer off-screen images anddecoding="async"to prevent the main thread from blocking while the image decodes.
Optional: Adding a Multi-Tier WebP Fallback
While AVIF adoption is widespread in modern browsers, you can provide an intermediate WebP layer to capture older modern browsers before dropping down to baseline JPEG:
<picture>
<source srcset="image.avif" type="image/avif">
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="A descriptive description of the image" width="800" height="600" loading="lazy" decoding="async">
</picture>In this structure, an AVIF-capable browser downloads only the AVIF
file. A browser that supports WebP but not AVIF will bypass the first
source and load the WebP file. Any browser lacking support for both
modern formats will default to the standard JPEG file in the
<img> element.