你应该知道如何处理图片懒加载🖼️

862 阅读7分钟

原生懒加载原理

懒加载是一种网页性能优化的方式,能极大的提升用户体验。图片一直是影响网页性能的主要元凶,现在一张图片超过几兆已经是很经常的事了。如果每次进入页面就请求所有的图片资源,那么可能等图片加载出来用户也早就走了。所以,我们需要懒加载,进入页面的时候,只请求可视区域的图片资源。

两个点:

  1. 全部加载的话会影响用户体验

  2. 浪费用户的流量,有些用户并不像全部看完,全部加载会耗费大量流量

1. 和懒加载相关的API

document.documentElement.clientHeight //获取屏幕可视区域的高度

MDN上的解释:

这个属性是只读属性,对于没有定义CSS或者内联布局盒子的元素为0,否则,它是元素内部的高度(单位像素),包含内边距,但不包括水平滚动条、边框和外边距。

image.png

element.offsetTop // 获取元素相对于文档顶部的高度

MDN上的解释:

HTMLElement.offsetTop 为只读属性,它返回当前元素相对于其 offsetParent 元素的顶部内边距的距离。

document.documentElement.scrollTop // 获取浏览器窗口顶部与文档顶部之间的距离,也就是滚动条滚动的距离

MDN上的解释:

Element.scrollTop 属性可以获取或设置一个元素的内容垂直滚动的像素数。

一个元素的 scrollTop 值是这个元素的内容顶部(卷起来的)到它的视口可见内容(的顶部)的距离的度量。当一个元素的内容没有产生垂直方向的滚动条,那么它的 scrollTop 值为0

通过上面三个API,我们获得了三个值:可视区高度、元素相对于其父元素容器顶部的距离、浏览器窗口顶部与容器元素顶部的距离也就是滚动条滚动的高度。

可能到这里还有一些人不知道怎么实现,我们还是用图来展示一下:

无标题-2022-01-15-2104.png

大家看了这张图,应该一下就能明白过来了。所以我们就得出了一个判断公式:

如果:offsetTop-scroolTop<clientHeight,则图片进入了可视区内,则被请求。

2.代码实现

下面的代码就是根据以上公式实现的:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>图片懒加载</title>
    <style>
        img {
            display: block;
            width: 100%;
            height: 300px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
  <img data-src="https://cdn.pixabay.com/photo/2021/04/10/22/13/tulip-6168238__340.jpg" alt="">
  <img data-src="https://cdn.pixabay.com/photo/2021/04/07/15/18/kingfisher-6159371__340.jpg" alt="">
  <img data-src="https://cdn.pixabay.com/photo/2021/04/11/07/22/red-fox-6168890__340.jpg" alt="">
  <img data-src="https://cdn.pixabay.com/photo/2021/04/01/07/56/flowers-6141542__340.jpg" alt="">
  <img data-src="https://cdn.pixabay.com/photo/2021/04/13/06/36/snow-6174775__340.jpg" alt="">
  <img data-src="https://cdn.pixabay.com/photo/2021/04/03/02/21/fashion-6146328__340.jpg" alt="">
  <img data-src="https://cdn.pixabay.com/photo/2021/04/10/17/53/cowboy-6167767__340.jpg" alt="">
  <img data-src="https://cdn.pixabay.com/photo/2021/04/02/05/11/mushrooms-6143786__340.jpg" alt="">
  <img data-src="https://cdn.pixabay.com/photo/2021/03/29/18/32/village-6134907__340.jpg" alt="">
  <img data-src="https://cdn.pixabay.com/photo/2021/04/12/14/00/winter-6172732__340.jpg" alt="">
  <img data-src="https://cdn.pixabay.com/photo/2014/04/14/20/11/pink-324175__340.jpg" alt="">
  <img data-src="https://cdn.pixabay.com/photo/2021/04/12/15/44/lake-6173043__340.jpg" alt="">
</body>
<script>
        var imgs = document.querySelectorAll('img');

        //offsetTop是元素与offsetParent的距离,循环获取直到页面顶部
        function getTop(e) {
            var T = e.offsetTop;
            while(e = e.offsetParent) {
                T += e.offsetTop;
            }
            return T;
        }

        function lazyLoad(imgs) {
            var H = document.documentElement.clientHeight;//获取可视区域高度
            var S = document.documentElement.scrollTop || document.body.scrollTop;
            for (var i = 0; i < imgs.length; i++) {
                if (H + S > getTop(imgs[i])) {
                    imgs[i].src = imgs[i].getAttribute('data-src');
                }
            }
        }

        window.onload = window.onscroll = function () { //onscroll()在滚动条滚动的时候触发
            lazyLoad(imgs);
        }
</script>
</html>

✔️ 注意:offsetTop是相对于父元素的,所以上面带有一个offsetParent。

更加方便快捷的实现方式

1.了解一个API

这种实现方式我们只需要了解一个API就行了:

getBoundingClientRect() //获取元素的大小及位置

MDN上的解释:

Element.getBoundingClientRect()  方法返回元素的大小及其相对于视口的位置。

如果是标准盒子模型,元素的尺寸等于width/height + padding + border-width的总和。如果box-sizing: border-box,元素的的尺寸等于 width/height

image.png

从这张图我们可以看出,元素是相对于左上角,而不是什么边距。

2.实现方式

通过上面的实验我们都知道,懒加载的一个重点就是要知道什么时候图片是进入了可视区内,那么就上面这张图而言,我们有什么方法判断图片进入了可视区呢。

其实很简单:我们先获取图片到可视区顶部的距离,并获取到可视区的高度

var bound = el.getBoundingClientRect();
var clientHeight = window.innerHeight;//这个和前面获取可视区高度的效果一样,只是兼容性问题

然后我们继续思考,当我们滚动条向下滚动的时候,bound.top值会变得越来越小,也就是图片到可视区顶部的距离也越来越小,所以当bound.top == clientHeight时,说明土片马上就要进入可视区了,只要我们在滚动,图片就会进入可视区,那么就需要请求资源了。也就是说,在bound.top<=clientHeight时,图片是在可视区域内的。

经过上面的思考,我们大致明白了如何实现,那么就来编写我们的代码了吧:

只需要把我们的js代码换成如下即可:

 var imgs = document.querySelectorAll('img');

        //用来判断bound.top<=clientHeight的函数,返回一个bool值
        function isIn(el) {
            var bound = el.getBoundingClientRect();
            var clientHeight = window.innerHeight;
            return bound.top <= clientHeight;
        } 
        //检查图片是否在可视区内,如果不在,则加载
        function check() {
            Array.from(imgs).forEach(function(el){
                if(isIn(el)){
                    loadImg(el);
                }
            })
        }
        function loadImg(el) {
            if(!el.src){
                var source = el.dataset.src;
                el.src = source;
            }
        }
        window.onload = window.onscroll = function () { //onscroll()在滚动条滚动的时候触发
            check();
        }

原生的图片懒加载就是如此。

现在谁还会用原生的呀,大家都是 Vue,React 来一梭子。没关系,我们接着学

Vue 图片懒加载

有现成的吗?有!

v-lazyload的使用

npm

安装

npm install vue-lazyload --save

main.js

loading: '/static/loading-svg/loading-bars.svg' ,后面是懒加载时候想要显示的图片

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import VueLazyLoad from 'vue-lazyload'

Vue.config.productionTip = false
Vue.use(VueLazyLoad, {
  loading: '/static/loading-svg/loading-bars.svg'
})

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

组件

<li v-for="(item, index) in goodsList" :key="index">
  <div class="pic">
    <a href="#">
       <img v-lazy="'/static/' + item.productImg" alt="">
    </a>
 </div>
</li>

我想要自己实现一个,行,满足你。

先来看一个知识点,自定义指令。

n.js
import Vue from 'vue'
// n 是指令的名字
Vue.directive('n', {
// 处理的函数
    bind: function (el, binding) {
        el.textContent = Math.pow(binding.value, 2)
    },
    update: function (el, binding) {
        el.textContent = Math.pow(binding.value, 2)
    }
})
使用的地方
<div class="" v-n="9">

v-imgLazy

使用 IntersectionObserver API实现。IntersectionObserver 对象的 observe() 方法向 IntersectionObserver 对象监听的目标集合添加一个元素。一个监听者有一组阈值和一个根, 但是可以监视多个目标元素,以查看这些目标元素可见区域的变化。简单来说可以监听dom元素进出可视区域,并且可以控制具体的变化。 具体使用请看 IntersectionObserverAPI:developer.mozilla.org/zh-CN/docs/…

新建一个directive用来存放自定义指令 directive/imgLazy.js

import baseImg from '@/assets/logo.png'

// 创建一个监听器
let observer = new IntersectionObserver((entries)=>{
  // entries是所有被监听对象的集合
  entries.forEach(entry =>{
  	// 判断被观察的对象(dom 元素)是否进入可视区域
    if(entry.isIntersecting){
      // 当被监听元素到临界值且未加载图片时触发
      !entry.target.isLoaded  && showImage(entry.target,entry.target.data_src)
    }
  })
})

function showImage(el,imgSrc){
  const img = new Image();
  img.src = imgSrc;
  img.onload = ()=>{
    el.src = imgSrc;
    el.isLoaded = true;
  }
}

export default {
  // 这里用inserted和bind都行,因为IntersectionObserver时异步的,以防意外还是用inserted好一点
  // inserted和bind的区别在于inserted时元素已经插入页面,能够直接获取到dom元素的位置信息。
  inserted(el,binding) {
    // 初始化时展示默认图片
    el.src = baseImg;
    // 将需要加载的图片地址绑定在dom上
    el.data_src = binding.value;
    observer.observe(el)
  },
  unbind(){
    // 停止监听
    observer.disconnect();
  }
}

在main.js中使用,注册全局指令 main.js

import imgLazy from '@/directive/imgLazy.js'
Vue.directive('imgLazy', imgLazy)

在组件中定义directives使用,给当前组件注册指令

<template>
  <div class='container'>
    <div v-for="(item,index) in imgSrc" :key="index" >
      <img v-imgLazy="item" >
    </div>
  </div>
</template>

<script>
import imgLazy from '@/directive/imgLazy.js'
export default {
  directives: {
    imgLazy: imgLazy,
  },
  data(){
    return {
      imgSrc:[
        "https://img.zcool.cn/community/01578c5f9d3a1011013fdcc7ea7b65.jpg@1280w_1l_2o_100sh.jpg",
        "https://img.zcool.cn/community/019d4e5f9d3a1411013fdcc77d222a.jpg@1280w_1l_2o_100sh.jpg",
        "https://img.zcool.cn/community/01a4c95f9d3a1911013fdcc7e9527c.jpg@1280w_1l_2o_100sh.jpg",
        "https://img.zcool.cn/community/014c365f9d3a1c11013ee04d5aabd7.jpg@1280w_1l_2o_100sh.jpg",
        "https://img.zcool.cn/community/01914f5f61b04411013e4584755182.jpg@1280w_1l_2o_100sh.jpg",
        "https://img.zcool.cn/community/01cb855f61b04911013e45844abf63.jpg@1280w_1l_2o_100sh.jpg",
        "https://img.zcool.cn/community/01c09d5f75af5311013e4584777726.jpg@1280w_1l_2o_100sh.jpg",
        "https://img.zcool.cn/community/0140f35f50918111013e3187d6f47e.jpg@1280w_1l_2o_100sh.jpg",
        "https://img.zcool.cn/community/01578c5f9d3a1011013fdcc7ea7b65.jpg@1280w_1l_2o_100sh.jpg",
        "https://img.zcool.cn/community/019d4e5f9d3a1411013fdcc77d222a.jpg@1280w_1l_2o_100sh.jpg",
        "https://img.zcool.cn/community/01a4c95f9d3a1911013fdcc7e9527c.jpg@1280w_1l_2o_100sh.jpg",
        "https://img.zcool.cn/community/014c365f9d3a1c11013ee04d5aabd7.jpg@1280w_1l_2o_100sh.jpg",
        "https://img.zcool.cn/community/01914f5f61b04411013e4584755182.jpg@1280w_1l_2o_100sh.jpg",
        "https://img.zcool.cn/community/01cb855f61b04911013e45844abf63.jpg@1280w_1l_2o_100sh.jpg",
        "https://img.zcool.cn/community/01c09d5f75af5311013e4584777726.jpg@1280w_1l_2o_100sh.jpg",
        "https://img.zcool.cn/community/0140f35f50918111013e3187d6f47e.jpg@1280w_1l_2o_100sh.jpg",
      ]
    }
  }
}
</script>

<style scoped>
img{
  width: 200px;
  height: 200px;
}
</style>

具体的效果如下: 在这里插入图片描述


既然 Vue 都说了,那 React 也不能少呀。不要厚此薄彼嘛。

封装 React 图片懒加载组件

import React from 'react'

const css = {
  box: {
    height: '400px',
    border: '1px solid pink',
    overflowY: 'scroll',
  },
  imageBox: {
    width: '500px',
    height: '500px',
    margin: '20px auto',
  },
}

// 要加载的 img 图片(jsx)
const images = []
// 图片的 ref(操作dom时用)
const refs = []

// 添加4张待加载的图片
for (let i = 0; i < 4; i++) {
  // 新建空 ref
  const ref = React.createRef()
  // 放入 ref 数组
  refs.push(ref)
  // 新建 img jsx 放入 images (图片地址不放入 src 而是放入 自定义属性 data-src)
  images.push(
    <div style={css.imageBox} key={i}>
      <img ref={ref} data-src={`https://pschina.github.io/src/assets/images/${i}.jpg`} alt="" />
    </div>
  )
}

// 这是触发时机 0.01代表出现 1%的面积出现在可视区触发一次回掉函数 threshold = [0, 0.25, 0.5, 0.75]  表示分别在0% 25% 50% 75% 时触发回掉函数
const threshold = [0.01]

// 利用 IntersectionObserver 监听元素是否出现在视口
const io = new IntersectionObserver((entries) => { // 观察者
  // entries 是被监听的元素集合它是一个数组
  entries.forEach((item) => {
    // intersectionRatio 是可见度 如果当前元素不可见就结束该函数。
    console.log(item.intersectionRatio)
    if (item.intersectionRatio <= 0) return 
    const { target } = item
    // 将 h5 自定义属性赋值给 src (进入可见区则加载图片)
    target.src = target.dataset.src
  })
}, {
  // 添加触发时机数组
  threshold,
});

// onload 函数
const onload = () => {
  refs.forEach((item) => {
    // 添加需要被观察的元素
    io.observe(item.current)
  })
}

// 定义懒加载纯函数组件
// 为了监听页面加载完毕 定义了一个img 利用 onerror 函数替代 onlaod {src需填写一个不存在图片的路径}
const LazyLoadPage = () => (
  <div style={css.box}>
    {images}
    <img onError={onload} src="" alt="" />
  </div>
)

export default LazyLoadPage

在这里插入图片描述


2023.10.23 更新

Vue3 封装 useLazyImageLoader hook

import { onMounted } from "vue";
const options = {
  rootMargin: "0px",
  threshold: 0.5,
  once: true,
};

function callback(entries, observer) {
  entries.forEach((entry) => {
    if (entry.intersectionRatio <= 0) return;
    const img = entry.target;
    const src = img.getAttribute("data-src");

    img.setAttribute("src", src ?? "");
    observer.unobserve(img);
  });
}

export const useLazyImageLoader = (ref) => {
  const observer = new IntersectionObserver(callback, options);

  onMounted(() => {
    Object.keys(ref.value).forEach((e) => {
      observer.observe(ref.value[e])
    });
  });
};

参考文章:

zhuanlan.zhihu.com/p/55311726

www.jianshu.com/p/6e8a76e8f…