Last active
July 22, 2021 11:46
-
-
Save Luckyfella73/0e948b5738cd4b758768222f91eae242 to your computer and use it in GitHub Desktop.
WebP detect and WebP background-image with fallback
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
const dataAttributeWebPCheck = 'data-webp-support-flag'; | |
const selectorWebPCheck = `[${dataAttributeWebPCheck}]`; | |
const classnameHasSupport = 'webp-supported'; | |
const classnameHasNoSupport = 'webp-not-supported'; | |
let elements = null; | |
let hasWebPSupport = false; | |
async function supportsWebp() { | |
if (!window.createImageBitmap) return false; | |
const webpData = 'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA='; | |
const blob = await fetch(webpData).then((r) => r.blob()); | |
return createImageBitmap(blob).then( | |
() => true, | |
() => false, | |
); | |
} | |
const setClassnameFlags = () => { | |
elements = document.querySelectorAll(selectorWebPCheck); | |
const supportClassName = hasWebPSupport === true ? classnameHasSupport : classnameHasNoSupport; | |
for (let e = 0; e < elements.length; e += 1) { | |
elements[e].removeAttribute(dataAttributeWebPCheck); | |
elements[e].classList.add(supportClassName); | |
} | |
}; | |
async function initWebPCheck() { | |
if (await supportsWebp()) { | |
hasWebPSupport = true; | |
document.body.classList.add(classnameHasSupport); | |
setClassnameFlags(); | |
} else { | |
document.body.classList.add(classnameHasNoSupport); | |
setClassnameFlags(); | |
} | |
} | |
const init = () => { | |
if (document.querySelector(selectorWebPCheck) !== null) { | |
initWebPCheck(); | |
} | |
}; | |
export default { | |
init, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sets CSS classname
webp-supported
orwebp-not-supported
to body tag and all elements on page having the data attributedata-webp-support-flag
. So in css you can switch background-images using this classes.Example
HTML:
SCSS:
WebP detection based on https://davidwalsh.name/detect-webp by David Walsh which is based on https://gist.github.com/jakearchibald/6c43d5c454bc8f48f83d8471f45698fa by Jake Archibald