Skip to content

Instantly share code, notes, and snippets.

@bbottema
Created December 27, 2019 10:32
Show Gist options
  • Save bbottema/0f69871dbce86941cbeeced439339493 to your computer and use it in GitHub Desktop.
Save bbottema/0f69871dbce86941cbeeced439339493 to your computer and use it in GitHub Desktop.
Ways of detecting webp browser support
// works for all browsers
async function supportsWebp():Promise<boolean> {
const img = new Image();
return new Promise(resolve => {
img.onload = function () {resolve((img.width > 0) && (img.height > 0));};
img.onerror = function () {resolve(false);};
img.src = "data:image/webp;base64," + "UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA";
});
}
// doesn't work with Edge? Edge supports webp, but as self.createImageBitmap is not available, this functions returns false
async function supportsWebpOld():Promise<boolean> {
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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment