Last active
January 30, 2021 12:11
-
-
Save jacob-lcs/9e40beadb2d61ba2a644a6730d3cafdd to your computer and use it in GitHub Desktop.
判断当前宿主环境是否支持 webp
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 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