dev-resources.site
for different kinds of informations.
Detect AVIF image support to use in your CSS
AVIF is a next generation image format, in the moment to write this post, the support is only by Chrome 85 and Firefox 77 under a flag.
W3C are working in the CSS Images Module Level 4, and the new module will have an interesting feature, image-set
and we'll can define the image type.
.element {
background-image: image-set( "image.avif" type("image/avif"),
"image.webp" type("image/webp"),
"image.jpg" type("image/jpeg") );
}
With image-set
we'll can define different format and the browser render the first image format supported.
Until we have this awesome feature in the browsers, we can use JavaScript to detect the support, we'll to do a sample with the AVIF format.
The CSS
body {
background-color: #000;
background-repeat: no-repeat;
background-size: cover;
}
body.avif {
background-image: url(./images/lions.avif);
}
body.no-avif {
background-image: url(./images/lions.jpg);
}
I know that you can put the image in JPEG format directly in the body and overwrite the background-image if the browser supports it, but for the example I think it's clearer.
The JavaScript
async function supportsAvif() {
if (!this.createImageBitmap) return false
const avifData =
'data:image/avif;base64,AAAAFGZ0eXBhdmlmAAAAAG1pZjEAAACgbWV0YQAAAAAAAAAOcGl0bQAAAAAAAQAAAB5pbG9jAAAAAEQAAAEAAQAAAAEAAAC8AAAAGwAAACNpaW5mAAAAAAABAAAAFWluZmUCAAAAAAEAAGF2MDEAAAAARWlwcnAAAAAoaXBjbwAAABRpc3BlAAAAAAAAAAQAAAAEAAAADGF2MUOBAAAAAAAAFWlwbWEAAAAAAAAAAQABAgECAAAAI21kYXQSAAoIP8R8hAQ0BUAyDWeeUy0JG+QAACANEkA='
const blob = await fetch(avifData).then((r) => r.blob())
return createImageBitmap(blob).then(
() => true,
() => false
)
}
;(async () => {
const classAvif = (await supportsAvif()) ? 'avif' : 'no-avif'
document.body.classList.add(classAvif)
})()
Demo
Thanks
I want to thank Jon Sneyers and Kornel, true magicians of image coders/decoders, for their help with the option of a base64
of an image of AVIF format as optimized as possible.
Featured ones: