Skip to content

Instantly share code, notes, and snippets.

@nagman
Last active January 20, 2021 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nagman/9d934acd774cd5927129a8d11ece9689 to your computer and use it in GitHub Desktop.
Save nagman/9d934acd774cd5927129a8d11ece9689 to your computer and use it in GitHub Desktop.
Functions to detect browser support for new image formats (webp, avif...)
// https://stackoverflow.com/a/54631141/4936168
// https://github.com/leechy/imgsupport/blob/master/imgsupport.js
export type ImageFormat = 'avif' | 'webp' | 'jpg';
const samples: { [key in Exclude<ImageFormat, 'jpg'>]: string } = {
avif: 'AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKCBgANogQEAwgMg8f8D///8WfhwB8+ErK42A=',
webp: 'UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==', // lossless
};
const formats: Exclude<ImageFormat, 'jpg'>[] = ['avif', 'webp'];
export function supportsFormat(type: Exclude<ImageFormat, 'jpg'>): Promise<boolean> {
const img = new Image();
img.src = 'data:image/webp;base64,' + samples[type];
return new Promise((resolve) => {
img.onload = () => resolve(!!img.height);
img.onerror = () => resolve(false);
});
}
export async function checkBestImageFormat(): Promise<ImageFormat> {
const list = await Promise.all(
formats.map((f) => (supportsFormat(f) ? f : false)),
);
return list.filter(Boolean)[0] || 'jpg';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment