(编辑:jimmy 日期: 2024/11/17 浏览:2)
图片往往在加载前端项目中占大头,如何既不损失图片质量,又提升加载速度呢?
注册全局自定义指令
Vue.directive('img-condense', { bind: (el, binding, vnode) => { let src = el.getAttribute('src') let newSrc = compressImg(src, el) el.setAttribute('src', newSrc) } })
获取元素宽高和显示设备pixelRatio
let compressImg = (imgUrl, el) => { // 获取显示设备 pixelRatio let pixelRatio = window.devicePixelRatio let elWidth = elStyle.width * pixelRatio let elHeight = elStyle.height * pixelRatio let resize = '/resize' if (elWidth) { resize += `,w_${elWidth}` } if (elHeight) { resize += `,h_${elHeight}` } })
判断webp
let canUseWebp = document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0 let webp = '' if (canUseWebp) { webp = '/format,webp' }
质量降低至80%
let ossParam"htmlcode"><img v-img-condense alt="Vue logo" src="/UploadFiles/2021-04-02/logo.png">以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。