基于原生的图片懒加载

296 阅读2分钟

前言:

想监听某元素是否进入了视口 有一个新的 IntersectionObserver API,可以自动"观察"元素是否可见,Chrome 51+ 已经支持。由于可见(visible)的本质是,目标元素与视口产生一个交叉区,所以这个 API 叫做"交叉观察器"。

参考链接:www.ruanyifeng.com/blog/2016/1…

讲解此API

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

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

// 监听DOM元素
obs.observe(imgDom)
// 取消DOM监听
obs.unobserve(imgDom)

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

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

具体实现代码

1.我现在的项目基于Vue3 所以我- 基于vue3.0和IntersectionObserver封装懒加载指令src/components/library/index.js

// 当图片地址不正确 弄一个默认地址
import defaultImg from '@/assets/images/200.png'

// 指令
const defineDirective = (app) => {
  // 扩展自定义指令
  app.directive('lazyload', {
    // Vue2规则 :inserted
    // inserted () {}
    // Vue3规则:mounted
    mounted (el, bindings) {
      // el表示使用指令的DOM元素
      // bindings表示指令相关的信息
      // 指令的功能:实现图片的懒加载
      // 1、监听图片进入可视区
      const oberver = new IntersectionObserver(([{ isIntersecting }]) => {
        if (isIntersecting) {
          // 进入了可视区
          // 2、给图片的src属性赋值图片的地址
          el.src = bindings.value
          // 取消图片的监听
          oberver.unobserve(el)
          // 加载的图片失败了,显示默认的图片地址
          el.onerror = () => {
            // 显示默认图片
            el.src = defaultImg
          }
        }
      })
      oberver.observe(el)
    }
  })
}


// 
export default {
  install (app) {
  // 配的全局组件
    app.component(XtxSkeleton.name, XtxSkeleton)
    app.component(XtxCarousel.name, XtxCarousel)
    app.component(XtxMore.name, XtxMore)
    
  // 自定义指令挂上去
+    defineDirective(app)
  }
}

2.组件中使用 把img的src全改成v-lazyload

<img alt="" v-lazyload="cate.picture">