webp在项目中使用的好处就不在这里多说了, chrome性能优化指南上有详情的介绍。下面主要说下如何在项目中落地。css
使用picture
标签,这个是html5
新加的标签,浏览器支持状况,能够见caniusehtml
下面是具体的引用,picture
标签下有一个source
,眼熟的可能想到了video
标签下也有一个source
标签, source
的srcset
用来标注图片连接,type
为图片类型(浏览器根据type
类型判断支不支持此类型,从而决定是否加载), 从第1个source
开始判断,img
元素兜底。html5
img
元素兜底时,lazy-load
也是能够正常使用的,自身的class
也不受影响。git
<picture>
<source srcset="teal.png!750.webp" type="image/webp">
<img src="teal.png" data-original="" class="" />
</picture>
复制代码
对于不支持的浏览器要怎么处理呢,这里有两种解决方案:github
html
结构不动, 对于不支持picture
的浏览器,picture
标签并不解析,img
与picture
同级。因此css
里设置的善于picture
的选择器将无效。故这种方式适合img
样式结构简单的地方。同时因为不支持picture
,故source
里的2x/3x
,响应式也就用不了,只是简单的src fallback
。IE8下的结构,能够看到picture
并无被正确解析:web
<picture>
<source srcset="teal.png!750.webp" type="image/webp">
<img src="teal.png" />
<picture>
复制代码
/** * 检测user-agent是否支持webp图片 * @return thenable function */
const checkWebp = function () {
return new Promise(((resolve) => {
const img = new Image()
const dataUri = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA'
img.onload = function () {
const result = (img.width > 0) && (img.height > 0)
resolve(result)
}
img.onerror = function () {
resolve(false)
}
img.src = dataUri
}))
}
复制代码
JS polyfill
脚本picturefill来支持picture
原生功能,包括上面提到的响应式支持(media/2x/3x
等)<picture>
<source srcset="teal.png!750.webp" type="image/webp" media="(min-width: 768px)">
<source srcset="teal.png!750.webp 2x" type="image/webp">
<img src="teal.png" />
</picture>
复制代码
扩展阅读:chrome