Skip to content

Instantly share code, notes, and snippets.

@jacob-lcs
Last active Jan 30, 2021
Embed
What would you like to do?
判断当前宿主环境是否支持 webp
// 方法一,非异步方式
const supportWebP = (function () {
var canvas = typeof document === 'object' ? document.createElement('canvas') : {}
canvas.width = canvas.height = 1
return canvas.toDataURL ? canvas.toDataURL('image/webp').indexOf('image/webp') === 5 : false
})()
// 异步方式获取,比较适合系统中存在一个系统变量来保存结果
window.isSupportWebp = false; // 是否支持
(function() {
let img = new Image();
function getResult(event) {
// 如果进入加载且图片宽度为1(通过图片宽度值判断图片是否可以显示)
window.isSupportWebp = event && event.type === 'load' ? img.width == 1 : false;
}
img.onerror = getResult;
img.onload = getResult;
img.src = 'data:image/webp;base64,UklGRiQAAABXRUJQVlA4IBgAAAAwAQCdASoBAAEAAwA0JaQAA3AA/vuUAAA='; // 一像素图片
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment