DEV Community

Discussion on: Detect AVIF image support to use in your CSS

Collapse
 
mountainash profile image
Mountain/\Ash

I've combined your code with the older [very similar] webp code from ourcodeworld.com/articles/read/630... to create a version that will work for both AVIF and WebP.

async function supportsEncode() {
  const fallbackclass = 'old';
  if (!this.createImageBitmap) return fallbackclass;

  const avifData =
    'data:image/avif;base64,AAAAFGZ0eXBhdmlmAAAAAG1pZjEAAACgbWV0YQAAAAAAAAAOcGl0bQAAAAAAAQAAAB5pbG9jAAAAAEQAAAEAAQAAAAEAAAC8AAAAGwAAACNpaW5mAAAAAAABAAAAFWluZmUCAAAAAAEAAGF2MDEAAAAARWlwcnAAAAAoaXBjbwAAABRpc3BlAAAAAAAAAAQAAAAEAAAADGF2MUOBAAAAAAAAFWlwbWEAAAAAAAAAAQABAgECAAAAI21kYXQSAAoIP8R8hAQ0BUAyDWeeUy0JG+QAACANEkA=',
    webpData = 'data:image/webp;base64,UklGRiQAAABXRUJQVlA4IBgAAAAwAQCdASoCAAEAAQAcJaQAA3AA/v3AgAA=',
    avifblob = await fetch(avifData).then((r) => r.blob()),
    webpblob = await fetch(webpData).then((r) => r.blob());
  return createImageBitmap(avifblob).then(
    () => 'avif',
    () => {
      return createImageBitmap(webpblob).then(() => 'webp', () => fallbackclass)
    }
  )
};

(async () => {
  const classImg = await supportsEncode();
  document.body.classList.add(classImg);
})()
Enter fullscreen mode Exit fullscreen mode
  • Today in Safari 14.0.2 it returns old in the Tech Preview Safari 14.2 it returns webp
  • In Firefox 85.0.2 is returns webp and in Developer Edition 86.0b9 it returns avif
  • Chrome Version 88.0 returns avif as expected
Collapse
 
lili21 profile image
li.li

Chrome Version 112.0.5615.121 (Official Build) (x86_64) returns webp which is not right.

Collapse
 
mountainash profile image
Mountain/\Ash

Ensure you checkout the updated codepen code which was added to the comments 2yrs ago. It's returning correctly for the latest version of Chrome (aka, the version you've listed).

Collapse
 
mountainash profile image
Mountain/\Ash

Further to yesterday's comment; I've cleaned this up at codepen.io/mountainash/pen/eYBRpzV (not creating the WebP blob if the AVIF is OK)

Collapse
 
justinschmitz97 profile image
justinschmitz97

I just compared this to my snippet on avif.io/blog/tutorials/use-avif-in...
Your script is at 900 chars, mine is 600 chars. Is there any benefit I don't see? I'm not criticizing your work, I'm actually curious, cause then I'd implement your version with credits.

Thread Thread
 
mountainash profile image
Mountain/\Ash

I wasn't aware of your's; it's new to me (and this article and the comments section). Looks good -> use it.

Thread Thread
 
justinschmitz97 profile image
justinschmitz97

Awesome, thanks for clarifying, I appreciate it. :)