目录
今天翻video标签文档,看到里面的source可以根据类型加载支持格式的视频链接。突然就想起了一个问题,图片可以吗,我可以判断是否支持webp么?说干就干,顺路就摸到了picture标签。哈哈哈哈,看起来是有戏。
最容易搜索到的
如该文判断浏览器是否支持 webp 的几种解决方法,主要为:
-
使用 canvas 的 toDataURL 进行判断
就刚刚去查caniuse,发现了个大秘密。如下,就2022年8月19日的今天,大部分浏览器的新版本已经支持webp格式了,然而,toDataURL 出现了滞后,也就是说该方法不能准确的判断浏览器是否支持 webp


-
在服务端根据请求header信息判断浏览器是否支持webp
这个方法我认为是有效的,并且已经在我的博客站里面使用。我的网站支持WebP啦,当时也记录了webp的支持情况,可以去对比下。缺点是,依赖服务端。
-
通过加载一张 webp 图片进行判断
按评论这就是最准确的方法了。
我的方法
原理
利用picture标签自带的兼容性判断,以及currentSrc方法获取呈现的图像的 URL。如果浏览器支持webp,则加载type="image/webp"对应的图片链接。
源码
function webptest(callback) {
let picture = document.createElement('picture')
picture.innerHTML = '<picture style="display: none"> <source srcset="/webp" type="image/webp"> <img id="__webptest" src="/jpg" type="image/jpg" > </picture>'
document.body.append(picture)
let f = function () {
let src = document.getElementById('__webptest').currentSrc || document.getElementById('a').src
src = src.replace(window.location.origin+'/','')
callback(src=='webp')
}
document.getElementById('__webptest').onerror = f
document.getElementById('__webptest').onload = f
}
webptest(function(res){
alert(res)
console.log(res)
})
picture caniuse
记录 2022年8月19日

currentSrc caniuse
记录 2022年8月19日
