1.背景:

     前几天项目需求实现了图片瀑布流布局,就想着自己再实现图片的懒加载,瀑布流布局配合图片懒加载。

2.懒加载的意义

   图片懒加载为的是提升网页性能,减少图片在同一时间请求很多网络图片资源,当然是页面一次性展示了很多图片的情况,所以在这种情况下,为了提升网页性能,提高用户体验我们可以用懒加载来实现。

3.实现原理

   主要思路就是在可视区域内得图片进行加载,反之默认不做图片得请求,可以用我们本地自己定义得比较小得loading图代替(当然这个loading图片也会做网络请求,但是是我们自己定义的,那便可空,选的图会比较小,而且在同一时刻,相同图片只会请求一次),本次实现,源码里没有给默认的loading图片,而是把图片加载之前的样式,以及图片加载失败后的样式交给使用者自己定义

这里尝试了两种方案:

方案1: 传统实现图片懒加载,会去监听滚动条的变化,当图片进入可视区域内,通过监听当前图片以及滚动条位置,判断是否已经进入可视区域

主要用到:

window.addEventListener("scroll", (e) => {});  // 监听滚动
Element.getBoundingClientRect() // 方法会返回一个DOMRect对象,其包含了当前元素的大小,以及相对于视窗的位置信息

方案1 代码走起:

<template>
      <div>
        <img v-for="(item,i) in lazyImgs" style="width: 180px;height:240px;margin- 
          top:40px;display: inline-block;" :data-src="item"  :key="i" src=""   
        alt="">
      </div>
</template>
async mounted() {
    window.addEventListener("scroll", (e) => {
      // 这里做一个 节流 操作
      if (this.timer) return;
      this.timer = setTimeout(() => {
        this.query("img[data-src]").forEach((img) => {
          const rect = img.getBoundingClientRect();
          if (rect.top < window.innerHeight) {
            img.src = img.dataset.src;
            // 我们是通过img[data-src]查找所有img标签的,渲染后就删除data-src可减少forEach循环的计算成本
            img.removeAttribute("data-src"); 
          }
        });
        clearTimeout(this.timer);
        // 这里一定要把定时器置为 null
        this.timer = null
      }, 300);
    });
},
methods: {
  query(selector) {
     return Array.from(document.querySelectorAll(selector));
  },
}

上面方法是传统方法通过监听滚动条来实现

方案2: 利用监听器实现  

用到的api       IntersectionObserver    不了解的小伙伴自行百度一下 就是一个监听器,学名叫交叉观测器,可以监听任何元素,当元素进入可视区域内,便会触发回调函数

我这里封装成了组件 不多说上代码

<template>
  <div class="img-box">
    <img
      v-lazy="lazy"
      :data-src="src"
      src=""
      @load="loadImg"
      @error="error"
      alt=""
    />
    <slot v-if="slotShow"></slot>
    <slot name="err" v-if="!errFlag"></slot>
  </div>
</template>
<script>
export default {
  props: {
    src: {
      type: String,
      default: ''
    },
    // 是否懒加载
    lazy: {
      type: Boolean,
      default: false
    }
    // errorImg: {
    //   type: String,
    //   default: ''
    // }
  },
  data() {
    return {
      slotShow: true,
      errFlag: true
    }
  },
  // 定义指令
  directives: {
    'lazy':{
      inserted(el,{value}) {
      // 如果指令传过来得值是 false 就不做懒加载处理
      if(!value) return
      // el.style.backgroundColor = '#f9ccd4'
      // const imgSrc = el.src;
      const imgSrc = el.dataset.src;
      // el.src = "";
      // 观察者
      const observer = new IntersectionObserver(([{ isIntersecting }]) => {
        // console.log(aaa[0].boundingClientRect.top,'这是个啥');
        // 如果元素出现在可视区域内,和离开可视区域的时候被触发
        if (isIntersecting) {
          // 出现在可视区域,再加载图片
          el.src = imgSrc;
          el.dataset.flag = true
          // 停止观察
          observer.unobserve(el);
        }
      });
      // 开启观察(传入要观察的dom元素)
      observer.observe(el);
    },
    }
  },
  methods: {
    loadImg() {
      this.slotShow = false
    },
    error(e) {
      if(!e.srcElement.dataset.flag||!this.errFlag) return false
      console.log(e.srcElement.src,'这加载错误了');
      // 这里我们就不给设置失败后的图片了,留给使用者自行设置样式
      // e.srcElement.src = this.errorImg
      this.errFlag = false
      this.slotShow = false
    }
  }
}
</script>
<style lang="less" scoped>
.img-box {
  display: flex;
  position: relative;
  overflow: hidden;
}
img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>

需要用到的地方 引入组件

<template>
  <div>
    <!-- 图片懒加载最好设置图片高度,因为不管你是监听滚动条的方式,还是利用监听器api实现,都跟元素可视区域有关系,而高度就影响是否在可视区域内 -->
    <lazyImg style="width: 180px;height:240px;display: inline-block;" v-for="(item,i) in lazyImgs" :key="i" :src="item" lazy>
      <!-- 图片加载之前默认在图片元素上方展示的样式--自由发挥 -->
      <div class="slot-txt">加载中</div>
      <template #err>
        <!-- 图片加载失败后在上面展示的样式--- 自由发挥 -->
        <div class="slot-txt"><img src="@/assets/images/loading.gif" alt=""></div>
      </template>
    </lazyImg>
  </div>
</template>
<script>
import lazyImg from './components/lazyImg'
export default {
  components: {
    lazyImg
  },
  data: {
    return {
      lazyImgs: [
        'https://www.yuucn.com/wp-content/uploads/2023/04/1682189085-8ee5c1796d05f5a.jpeg',
        'https://www.yuucn.com/wp-content/uploads/2023/04/1682189092-8ee5c1796d05f5a.jpeg',
        'https://www.yuucn.com/wp-content/uploads/2023/04/1682189098-8ee5c1796d05f5a.jpeg',
        'https://www.yuucn.com/wp-content/uploads/2023/04/1682189105-8ee5c1796d05f5a.jpeg',
        'https://www.yuucn.com/wp-content/uploads/2023/04/1682189111-8ee5c1796d05f5a.jpeg',
        'https://www.yuucn.com/wp-content/uploads/2023/04/1682189118-8ee5c1796d05f5a.jpeg',
        'https://www.yuucn.com/wp-content/uploads/2023/04/1682189124-8ee5c1796d05f5a.jpeg'
      ]
    }
  }
}
</script>
<style lang="scss" scoped>
.slot-txt {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  background: #f9ccd4;
  z-index: 100;
}
</style>

好了,今天时间有些仓促,就到这里,完结,撒花,后期再润色,嘿嘿

经过反复测试,发现有点小坑,二期已解决,需要得小伙伴移步二期

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。