Open super-fool opened 4 years ago
首先,这种格式主要用于Chrome浏览器。
为了兼容IE,有两种使用方式:
WebP
图片的宽高是否能获取到var img = new Image();
img.onload = function() {
var isWebP = !!(img.height > 0 && img.width > 0);
checkWebP(isWebP);
}
img.onerror = function() {
checkWebP(isWebP);
}
function checkWebP(isWebP) {
var imgs = document.getElementsByTagName('img');
[...img].forEach( ele=>{
var webpSrc = ele.dataset.webp; // 获取WebP格式图片的src
var picSrc = ele.dataset.pic; // 获取普通的jpeg格式图片的src
var src = !!isWebP ? webpSrc : picSrc;
ele.setAttribute( 'src', 'src');
}
)
}
var checkWebp = function(){
try{
return (document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0);
}catch(err) {
return false;
}
}
isWebP = checkWebP() //isWebP为true则支持WebP,若为false则不支持WebP
插件: imagemin-webp
WebP
是谷歌推出的一种图片格式,在压缩方面比当前JPEG格式更优越。它是一种有损压缩的图片格式, 但是更高效。
它的优势在于:更高效,因为体积要比JPEG格式图像小40%。
一般我们可以用在头像,缩略图等地方。