Created
May 24, 2023 16:50
-
-
Save pingram3541/9cccec7d8e38b0706502cd9612e089bc to your computer and use it in GitHub Desktop.
Detect Webp browser support
This file contains hidden or 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
// check_webp_feature: | |
// 'feature' can be one of 'lossy', 'lossless', 'alpha' or 'animation'. | |
// 'callback(feature, isSupported)' will be passed back the detection result (in an asynchronous way!) | |
// see: https://stackoverflow.com/a/54631141/4845112 | |
function check_webp_feature(feature, callback) { | |
var kTestImages = { | |
lossy: "UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA", | |
lossless: "UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==", | |
alpha: "UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAARBxAR/Q9ERP8DAABWUDggGAAAABQBAJ0BKgEAAQAAAP4AAA3AAP7mtQAAAA==", | |
animation: "UklGRlIAAABXRUJQVlA4WAoAAAASAAAAAAAAAAAAQU5JTQYAAAD/////AABBTk1GJgAAAAAAAAAAAAAAAAAAAGQAAABWUDhMDQAAAC8AAAAQBxAREYiI/gcA" | |
}; | |
var img = new Image(); | |
img.onload = function () { | |
var result = (img.width > 0) && (img.height > 0); | |
callback(feature, result); | |
}; | |
img.onerror = function () { | |
callback(feature, false); | |
}; | |
img.src = "data:image/webp;base64," + kTestImages[feature]; | |
} | |
//example usage: | |
check_webp_feature('lossy', function (feature, isSupported) { | |
if (isSupported) { | |
// webp is supported, | |
// you can cache the result here if you want | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment