前景提要
后端用了 webp 格式,但是想让前端解决这个问题,所以有了这篇文章
有一个叫 webpjs 的插件,原理是如果存在 webp 且浏览器不兼容,则重新请求图片,将图片的 arraybuffer 转为 base64。
但是运行一次就要从 HTML 获取所有 img 标签进行转换,如果多个组件要用会出现就会重复发送请求,所以这里改了下源码,重新封装实现
吐槽一下: safari 简直就是新时代的 IE  
使用
首先下载
https://github.com/DougFlands/MyComponents/blob/master/webpjs-0.0.2.modified.js
然后注入到 index.html 里
tool.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
   |  export const checkWebps = () => {    try {     return (document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') === 0);   } catch (err) {     return false;   } }
  export const autoWebP = async (path) => {   const IsCheckWebps = localStorage.getItem('IsCheckWebps');   if (IsCheckWebps && IsCheckWebps === 'true') return path;   if (path.substr(path.length - 5, path.length) === ".webp") {     const res = await getImg(path)     return res.Data;   } else {     console.log(path)     return path   } }
  const getImg = (path) => {   return new Promise(function (resolve, reject) {     axios({ url: path, responseType: 'arraybuffer', }).then((res) => {       resolve(window.DecodeWebPImage(path, new Uint8Array(res.data), "js", 1))     })   }); }
 
  | 
 
使用
1 2 3
   | autoWebP(item.pic).then(res => {   item.pic = res })
  |