vue项目优化--图片懒加载--封装自定义指令

669 阅读1分钟

在这里插入图片描述

图片懒加载--封装自定义指令

目的

对于一些图片多的网站,图片懒加载是必不可少的一项性能优化,在图片进入可视区域再加载,这样可以避免不必要的性能损耗,增加网页的加载速度,在加载的时候处理一下加载失败

web API IntersectionObserver

原生 web API IntersectionObserver 简单介绍

// 创建观察对象实例
const observer = new IntersectionObserver(callback[, options])

const obs = new IntersectionObserver((entries, observer) => {
    // entries = [{isIntersecting: true}]
    
}, {})
obs.observe(imgDom)
obs.unobserve(imgDom)

// callback 被观察dom进入可视区离开可视区都会触发
// - 两个回调参数 entries , observer
// - entries 被观察的元素信息对象的数组 [{元素信息},{}],信息中isIntersecting判断进入或离开
// - observer 就是观察实例
// options 配置参数
// - 三个配置属性 root rootMargin threshold
// - root 基于的滚动容器,默认是document
// - rootMargin 容器有没有外边距
// - threshold 交叉的比例

// 实例提供两个方法
// observe(dom) 观察哪个dom
// unobserve(dom) 停止观察那个dom

指令封装

app.directive('lazyload', {
  mounted(el, binding) {
    const observer = new IntersectionObserver(
      ([{ isIntersecting }]) => {
        if (isIntersecting) {
          el.src = binding.value
          observer.unobserve(el)
          el.onerror = () => {
            el.src = defaultImg
          }
        }
      },
      {
        threshold: 0.01
      }
    )
    observer.observe(el)
  }
})

在标签内使用

使用时,v-自定义指令名称

<img v-lazyload="http://xxxxxxxx.png" alt="" />