Skip to content

Instantly share code, notes, and snippets.

@adomaskizogian
Created June 15, 2023 11:41
Show Gist options
  • Select an option

  • Save adomaskizogian/5476d46698176c3c97df29b7c426ef72 to your computer and use it in GitHub Desktop.

Select an option

Save adomaskizogian/5476d46698176c3c97df29b7c426ef72 to your computer and use it in GitHub Desktop.
let isWebpSupportedInstance = null;
const isWebpSupported = async (): Promise<boolean> => {
if (isWebpSupportedInstance !== null) {
return isWebpSupportedInstance;
}
if(checkWebpDecoding){
isWebpSupportedInstance = true;
} else if (await checkWebpLossySupport()){
isWebpSupportedInstance = true;
} else {
isWebpSupportedInstance = false;
}
return isWebpSupportedInstance;
};
export default isWebpSupported;
const checkWebpDecoding = () => {
const elem = document.createElement('canvas');
if (!!(elem.getContext && elem.getContext('2d'))) {
return elem.toDataURL('image/webp').indexOf('data:image/webp') === 0;
}
return false;
};
const checkWebpLossySupport = (): Promise<boolean> => {
const img = new Image();
return new Promise(resolve => {
img.onload = function () {
const result = (img.width > 0) && (img.height > 0);
resolve(result);
};
img.onerror = function () {
resolve(false);
};
img.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment