Created
May 30, 2017 15:49
-
-
Save XOP/0ce815a40621ec4723c879d8e664d8e9 to your computer and use it in GitHub Desktop.
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
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