Last active
June 6, 2024 00:32
-
-
Save RReverser/03d14b21f3e88b7ea2782b257dae9a09 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice. This code is working for me. Good Job
Thanks 🙌