Skip to content

Instantly share code, notes, and snippets.

@Luckyfella73
Last active July 22, 2021 11:46
Show Gist options
  • Save Luckyfella73/0e948b5738cd4b758768222f91eae242 to your computer and use it in GitHub Desktop.
Save Luckyfella73/0e948b5738cd4b758768222f91eae242 to your computer and use it in GitHub Desktop.
WebP detect and WebP background-image with fallback
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,
};
@Luckyfella73
Copy link
Author

Luckyfella73 commented Jul 21, 2021

Sets CSS classname webp-supported or webp-not-supported to body tag and all elements on page having the data attribute data-webp-support-flag. So in css you can switch background-images using this classes.

Example

HTML:

<div
  class="item-having-bg-image"
  data-webp-support-flag
></div>

SCSS:

.item-having-bg-image {
  width: 100%;
  height: 420px;
  background-position: center center;
  background-size: cover;

  &.webp-supported {
    background-image: url('https://picsum.photos/200/400.webp');
  }

  &.webp-not-supported {
    background-image: url('https://picsum.photos/200/400.jpg');
  }
}

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

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