Detect WEBP Support with JavaScript

Image optimization is a huge part of improving front-end performance.  We’ve traditionally used JPG/JPEG, GIF, and PNG images but Google and the Chrome team developed the WEBP format which crunches file size and optimizes rendering.  If you go to a site like GIPHY in Chrome you’ll be served a WEBP, but if you go to […]

The post Detect WEBP Support with JavaScript appeared first on David Walsh Blog.

Image optimization is a huge part of improving front-end performance.  We’ve traditionally used JPG/JPEG, GIF, and PNG images but Google and the Chrome team developed the WEBP format which crunches file size and optimizes rendering.  If you go to a site like GIPHY in Chrome you’ll be served a WEBP, but if you go to the same page in Firefox you’ll be served a GIF.  Since GIPHY lazy loads its images, GIPHY has the opportunity to use WEBP feature detection with JavaScript.

Googler and Service Worker pioneer Jake Archibald recently tweeted a snippet showing how you can use a service worker to detect WEBP support:

async function supportsWebp() { if (!self.createImageBitmap) return false; const webpData = 'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA='; const blob = await fetch(webpData).then(r => r.blob()); return createImageBitmap(blob).then(() => true, () => false);
} (async () => { if(await supportsWebp()) { console.log('does support'); } else { console.log('does not support'); }
})();

Jake fetches a valid WEBP data URI to determine if the browser supports WEBP — genius!  His script also uses async / await to handle promises which I will be covering soon on this blog.  Note that this code works outside a service worker, so you can use it anywhere within your own projects.

If your site is heavy on imagery, consider formatting your images with WEBP; Chrome’s market share is so large that it will definitely be worth it.  If you like small tips like this, be sure to follow Jake on Twitter!

Rojenx is a leading concept artist who work appears in games and publications

Check out his personal gallery here

In other news …

This site uses Akismet to reduce spam. Learn how your comment data is processed.