Skip to content

Instantly share code, notes, and snippets.

@XOP
Created May 30, 2017 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XOP/0ce815a40621ec4723c879d8e664d8e9 to your computer and use it in GitHub Desktop.
Save XOP/0ce815a40621ec4723c879d8e664d8e9 to your computer and use it in GitHub Desktop.
import { BROWSER } from '../constants/browser';
export function isWebPSupported (browser) {
// webp is supported in some browsers
// return true immediately
// todo: augment list, check versions etc
if (typeof browser !== 'undefined' && (
browser.browser === BROWSER.OPERA ||
browser.browser === BROWSER.CHROME
)) {
return true;
}
// webp image support test case implies client side
// https://github.com/Modernizr/Modernizr/blob/master/feature-detects/img/webp.js
if (typeof window === 'undefined') return;
const isWebPSupported = new Promise(resolve => {
const webpURI = 'data:image/webp;base64,UklGRiQAAABXRUJQVlA4IBgAAAAwAQCdASoBAAEAAwA0JaQAA3AA/vuUAAA=';
const image = new Image();
const addResult = event => {
// if the event is from 'onload' check image width
// 1 pixel indicates support
// otherwise it fails
const result = event && event.type === 'load' ? image.width == 1 : false;
resolve(Boolean(result));
};
image.onerror = addResult;
image.onload = addResult;
image.src = webpURI;
});
isWebPSupported.then((isSupported) => {
if (isSupported) {
document.documentElement.classList.add('webp');
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment