This is a space that holds a collection of my personal work and ideas

Serve Images in Next-gen Formats

Posted on 01/22/2021

Serving smaller images without sacrificing the resolution quality could be finally achieved with the next-gen formats. This article introduces three common next-gen formats and a tip to have fallback images when the browser doesn't support those.

Browser compatibility

Format Chrome FireFox Edge Safari IE11
WebP Y Y Y N N
AVIF Y Y N N N
Jpeg 2000 N N N Y N
Jpeg XR N N N N Y

Fallback

Based on the majority of the browsers support WebP format, we could default to use webp format for all images and set up fallback for universal Jpeg format.

HTML element fallback

<img alt="image description" 
     src="image.webp" 
     onerror="this.src=image.jpg" />

CSS background image fallback

/* default fallback when 'image-set()' is not supported */
background-image: url('image.jpg');
/* default to AVIF and if not supported, try WebP, etc.. */
background-image: image-set( 
  "image.avif" type("image/avif"),  
  "image.webp" type("image/webp"),
  "image.jp2"  type("image/jp2"),
  "image.jxr"  type("image/jxr"),
  "image.jpg"  type("image/jpeg")
);

Read on GitHub