Skip to content

Instantly share code, notes, and snippets.

@wojtekmaj
Last active October 25, 2022 17:33
Show Gist options
  • Save wojtekmaj/d30c5b2d637945003e273d2d39a5e3b4 to your computer and use it in GitHub Desktop.
Save wojtekmaj/d30c5b2d637945003e273d2d39a5e3b4 to your computer and use it in GitHub Desktop.
Image format feature detection
const isSafari = // ...
function getIsSupported(src) {
return new Promise((resolve) => {
const image = new Image();
image.onload = () => {
const isSupported = image.width > 0 && image.height > 0;
resolve(isSupported);
};
image.onerror = () => {
resolve(false);
};
image.src = src;
});
}
const avifString =
'data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABgAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACBtZGF0EgAKCBgADsgQEDRgMgof8GAACwAACIU0';
const webpString =
'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
const animatedWebpString =
'data:image/webp;base64,UklGRlIAAABXRUJQVlA4WAoAAAASAAAAAAAAAAAAQU5JTQYAAAD/////AABBTk1GJgAAAAAAAAAAAAAAAAAAAGQAAABWUDhMDQAAAC8AAAAQBxAREYiI/gcA';
export const isAvifSupported = await getIsSupported(avifString);
export const isWebpSupported = await getIsSupported(webpString);
export const isWebmSupported =
/**
* While Safari theoretically supports animated WebM videos, it displays transparent videos
* incorrectly.
*/
!isSafari && document.createElement('video').canPlayType('video/webm');
export const isAnimatedWebpSupported = await getIsSupported(animatedWebpString);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment