Skip to content

Instantly share code, notes, and snippets.

@RReverser
Last active June 6, 2024 00:32
Show Gist options
  • Save RReverser/03d14b21f3e88b7ea2782b257dae9a09 to your computer and use it in GitHub Desktop.
Save RReverser/03d14b21f3e88b7ea2782b257dae9a09 to your computer and use it in GitHub Desktop.
async function supportsImgType(type) {
// Create
//
// <picture>
// <source srcset="data:,x" type="{type}" />
// <img />
// </picture>
//
// (where "data:,x" is just a minimal URL that is valid but doesn't trigger network)
let img = document.createElement('img');
document.createElement('picture').append(
Object.assign(document.createElement('source'), {
srcset: 'data:,x',
type
}),
img
);
// Wait a single microtick just for the `img.currentSrc` to get populated.
await 0;
// At this point `img.currentSrc` will contain "data:,x" if format is supported and "" otherwise.
return !!img.currentSrc;
}
for (let type of ['image/png', 'image/jpeg', 'image/webp', 'image/avif']) {
supportsImgType(type).then(supported => console.log(`${type}: ${supported}`));
}
// image/png: true
// image/jpeg: true
// image/webp: true
// image/avif: false
@KevinToala
Copy link

Nice. This code is working for me. Good Job
Thanks 🙌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment