首页/文章/javascript

图片懒加载的实现方法

2024-08-06
22198 分钟
...

图片作为前端开发中不可或缺的元素,其加载速度对用户体验有着重要影响。然而,大量的图片加载不仅会消耗用户流量,还会导致页面加载缓慢,影响用户体验。为了解决这个问题,图片懒加载技术应运而生

图片懒加载(Lazy Loading)是一种优化网页性能的技术,它通过延迟加载图片,即在图片即将进入可视区域时才开始加载,从而减少页面初始加载时间,提高页面响应速度。

图片懒加载的实现原理主要基于以下几个关键点:

  • 滚动事件监听: 图片懒加载的核心是通过监听浏览器的滚动事件(scroll事件)。当用户滚动页面时,会触发这个事件。

  • 可视区域检测: 在滚动事件触发时,需要检测每个图片元素是否已经进入或即将进入浏览器的可视区域。这通常通过以下几种方法实现:

    • 基于Element的getBoundingClientRect()方法:这个方法可以获取元素的位置和尺寸信息,通过计算元素相对于视口的位置,可以判断元素是否在可视区域内。

    • Intersection Observer API:这是一个现代的API,可以异步观察目标元素与其祖先元素或顶级文档视口的交叉状态。它提供了更加简洁和高效的方式来监听元素是否进入可视区域。

    • 条件加载: 当检测到图片即将进入可视区域时,才开始加载这张图片。这样可以避免在页面初始加载时加载所有图片,从而减少初始加载时间和内存消耗。

    • 资源替换: 在图片检测到即将进入可视区域时,使用JavaScript动态地将图片的src属性设置为实际的图片URL。如果使用占位符(如低分辨率图片或单色图片),则在加载完成后将其替换为实际的图片资源。

利用滚动事件监听 + getBoundingClientRect

原理: 图片dom 预先不设置src属性值,而新增自定义属性 wait-render值为true,初始化 预渲染3张,监听dom滚动事件,当到达可视范围域,开始加载图片 设置图片的 src 属性为实际图片 URL,并删除wait-render属性

使用vue3 实现,注意要点

  1. 滚动事件可用 @scroll监听
  2. 循环中的dom用ref的方式获取可以利用ref绑定一个方法,然后插入到数组中备用
  3. 初始化和后续监听中有重复逻辑 抽离公用设置图片setImg,参数为方法返回满足条件
<template>
  <div ref="scrollContainer" @scroll="lazyLoadImages" class="image-container">
    <img :ref="getImg" v-for="(image, index) in images" :key="image" :wait-render="true" alt="图片" />
  </div>
</template>

<script setup>
import {  ref } from 'vue';

const scrollContainer = ref(null);

const images = ref([
  "http://e.hiphotos.baidu.com/image/pic/item/a1ec08fa513d2697e542494057fbb2fb4316d81e.jpg",
  "http://c.hiphotos.baidu.com/image/pic/item/30adcbef76094b36de8a2fe5a1cc7cd98d109d99.jpg",
  "http://h.hiphotos.baidu.com/image/pic/item/7c1ed21b0ef41bd5f2c2a9e953da81cb39db3d1d.jpg",
  "http://g.hiphotos.baidu.com/image/pic/item/55e736d12f2eb938d5277fd5d0628535e5dd6f4a.jpg",
  "http://e.hiphotos.baidu.com/image/pic/item/4e4a20a4462309f7e41f5cfe760e0cf3d6cad6ee.jpg",
  "http://b.hiphotos.baidu.com/image/pic/item/9d82d158ccbf6c81b94575cfb93eb13533fa40a2.jpg",
  "http://e.hiphotos.baidu.com/image/pic/item/4bed2e738bd4b31c1badd5a685d6277f9e2ff81e.jpg",
  "http://g.hiphotos.baidu.com/image/pic/item/0d338744ebf81a4c87a3add4d52a6059252da61e.jpg",
  "http://a.hiphotos.baidu.com/image/pic/item/f2deb48f8c5494ee5080c8142ff5e0fe99257e19.jpg",
  "http://f.hiphotos.baidu.com/image/pic/item/4034970a304e251f503521f5a586c9177e3e53f9.jpg",
  "http://b.hiphotos.baidu.com/image/pic/item/279759ee3d6d55fbb3586c0168224f4a20a4dd7e.jpg",
  "http://a.hiphotos.baidu.com/image/pic/item/e824b899a9014c087eb617650e7b02087af4f464.jpg",
  "http://c.hiphotos.baidu.com/image/pic/item/9c16fdfaaf51f3de1e296fa390eef01f3b29795a.jpg",
  "http://d.hiphotos.baidu.com/image/pic/item/b58f8c5494eef01f119945cbe2fe9925bc317d2a.jpg",
  "http://h.hiphotos.baidu.com/image/pic/item/902397dda144ad340668b847d4a20cf430ad851e.jpg",
  "http://b.hiphotos.baidu.com/image/pic/item/359b033b5bb5c9ea5c0e3c23d139b6003bf3b374.jpg",
  "http://a.hiphotos.baidu.com/image/pic/item/8d5494eef01f3a292d2472199d25bc315d607c7c.jpg",
  "http://b.hiphotos.baidu.com/image/pic/item/e824b899a9014c08878b2c4c0e7b02087af4f4a3.jpg",
  "http://g.hiphotos.baidu.com/image/pic/item/6d81800a19d8bc3e770bd00d868ba61ea9d345f2.jpg",
]);
let refImgs = ref([])

function getImg (el) {
  console.log('el', el)
  if (el) {
    refImgs.value.push(el)
  }
}

const lazyLoadImages = () => {
  
  const windowHeight = window.innerHeight;
  
  setImg((image, index) => {
    let img = refImgs.value[index]
    if(!img.getAttribute('wait-render')){
      return false
    }
    
    const imgTop = img.getBoundingClientRect().top;
    if (imgTop >= windowHeight){
      return false 
    }
    
    
    return true
  })
};

const setImg = (func = () => { }) => {
  images.value.forEach((image, index) => {
    if (func(image, index)) {
      const img = refImgs.value[index]
      img.src = image;
      
      img.removeAttribute('wait-render');
    }
  })
}
onMounted(() => {
  setImg((image, index) => {
    return index < 3
  })
});
onUnmounted(() => {
});
</script>

<style>
.image-container {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  overflow-y: scroll;
}

img {
  width: 100%;
  display: block;
  margin-bottom: 20px;
}
</style>

效果展示

Intersection Observer

从上图中滚动到加载图片的效果分析,看起来并不怎么丝滑,加载时机也不是很准确,以下是优化分析

  • 1.当前代码中,图片加载是按顺序进行的,这可能导致滚动到页面的底部时,页面加载速度变慢。可以考虑使用异步加载或分批加载图片,以提高用户体验。使用Intersection Observer API代替手动计算图片位置,这样可以更精确地控制图片加载时机。
  • 2.refImgs数组用于存储图片DOM元素的引用,但这个数组并不需要响应式。可以将它改为普通的JavaScript数组。(这个确实,所以考虑连这个refImgs变量声明都省了,直接用父级节点来获取子集scrollContainer.children)

修改之前 先了解下 Intersection Observer这个api

Intersection Observer API

它一个现代浏览器的API,用于异步观察目标元素与其祖先元素或顶级文档视窗(viewport)交叉状态的变化。这个API允许开发者在不使用轮询(polling)的情况下,高效地检测元素是否进入、离开或部分进入视窗。

1.基本概念

  • 目标元素(Target Element):想要观察的元素。
  • 祖先元素(Ancestor Element):目标元素的父元素或更上层的元素,或者是整个文档。
  • 视窗(Viewport):浏览器窗口的可见部分。

2.事件

  • 当目标元素与视窗交叉的状态发生变化时,会触发回调函数。以下是可能发生的事件:

  • 进入视窗(Enter the viewport):目标元素首次进入视窗。

  • 离开视窗(Leave the viewport):目标元素完全离开视窗。

  • 部分进入视窗(Partially enter the viewport):目标元素部分进入视窗。

3.使用方法

以下是一个简单的Intersection Observer API的使用示例:


let observer = new IntersectionObserver((entries, observer) => {
  entries.forEach(entry => {
    
    if (entry.isIntersecting) {
      console.log('元素已进入视窗');
      
    } else {
      console.log('元素已离开视窗');
      
    }
  });
}, {
  
  threshold: 0.5
});


observer.observe(document.getElementById('target-element'));



开始改造

下面利用 Intersection Observer改造后的完整代码

注意 图片要给个默认高度来撑开父级元素,否则初始化的时候图 都堆积在一起, 所以Intersection Observer会判定在可视窗口内的img 造成过度加载。就达不到想要的效果了

<template>
  <div ref="scrollContainer" class="image-container">
    <img v-for="(image, index) in images" :key="index" :data-src="image" alt="图片" />
  </div>
</template>

<script setup>
import { ref } from 'vue';

const images = ref([
  "http://e.hiphotos.baidu.com/image/pic/item/a1ec08fa513d2697e542494057fbb2fb4316d81e.jpg",
  "http://c.hiphotos.baidu.com/image/pic/item/30adcbef76094b36de8a2fe5a1cc7cd98d109d99.jpg",
  "http://h.hiphotos.baidu.com/image/pic/item/7c1ed21b0ef41bd5f2c2a9e953da81cb39db3d1d.jpg",
  "http://g.hiphotos.baidu.com/image/pic/item/55e736d12f2eb938d5277fd5d0628535e5dd6f4a.jpg",
  "http://e.hiphotos.baidu.com/image/pic/item/4e4a20a4462309f7e41f5cfe760e0cf3d6cad6ee.jpg",
  "http://b.hiphotos.baidu.com/image/pic/item/9d82d158ccbf6c81b94575cfb93eb13533fa40a2.jpg",
  "http://e.hiphotos.baidu.com/image/pic/item/4bed2e738bd4b31c1badd5a685d6277f9e2ff81e.jpg",
  "http://g.hiphotos.baidu.com/image/pic/item/0d338744ebf81a4c87a3add4d52a6059252da61e.jpg",
  "http://a.hiphotos.baidu.com/image/pic/item/f2deb48f8c5494ee5080c8142ff5e0fe99257e19.jpg",
  "http://f.hiphotos.baidu.com/image/pic/item/4034970a304e251f503521f5a586c9177e3e53f9.jpg",
  "http://b.hiphotos.baidu.com/image/pic/item/279759ee3d6d55fbb3586c0168224f4a20a4dd7e.jpg",
  "http://a.hiphotos.baidu.com/image/pic/item/e824b899a9014c087eb617650e7b02087af4f464.jpg",
  "http://c.hiphotos.baidu.com/image/pic/item/9c16fdfaaf51f3de1e296fa390eef01f3b29795a.jpg",
  "http://d.hiphotos.baidu.com/image/pic/item/b58f8c5494eef01f119945cbe2fe9925bc317d2a.jpg",
  "http://h.hiphotos.baidu.com/image/pic/item/902397dda144ad340668b847d4a20cf430ad851e.jpg",
  "http://b.hiphotos.baidu.com/image/pic/item/359b033b5bb5c9ea5c0e3c23d139b6003bf3b374.jpg",
  "http://a.hiphotos.baidu.com/image/pic/item/8d5494eef01f3a292d2472199d25bc315d607c7c.jpg",
  "http://b.hiphotos.baidu.com/image/pic/item/e824b899a9014c08878b2c4c0e7b02087af4f4a3.jpg",
  "http://g.hiphotos.baidu.com/image/pic/item/6d81800a19d8bc3e770bd00d868ba61ea9d345f2.jpg",
]);
const scrollContainer = ref(null);


let observer = null;


function loadImage(imageElement) {
  
  const src = imageElement.dataset.src;
  if (src) {
    imageElement.src = src;
    imageElement.removeAttribute('data-src');
  }
}


 * @param {Function} entries 一个数组,包含每个被观察元素的交叉信息。
 * @param {Number} observer IntersectionObserver 实例本身。
 */
const observerCallback = (entries, observer) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      loadImage(entry.target);
      observer.unobserve(entry.target);
    }
  });
};

onMounted(() => {
  
  observer = new IntersectionObserver(observerCallback, {
    root: scrollContainer.value, 
    threshold: 0.1 
  });
  
  images.value.forEach((image, index) => {
    const imgElement = scrollContainer.value.children[index];
    observer.observe(imgElement);   
  });
});

onUnmounted(() => {
  if (observer) {
    observer.disconnect(); 
  }
});

</script>

<style>
.image-container {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  overflow-y: scroll;
}

img {
  width: 100%;
  height: 500px;
  display: block;
  margin-bottom: 20px;
  object-fit: cover;
}
</style>

效果图

这样看起来就丝滑多了,加载时机也很准确,但每次使用 都要写这么多逻辑是不是很繁琐,用起来也不是很方便,能不能封装起来,让使用更加简洁和减少代码量书写呢,其实可以,而且不用重复造轮子,已经有成熟的组件库了,下面说一下 vue3-lazyload

vue3-lazyload

vue3-lazyload 是一个基于 Vue 3 的懒加载组件,它允许你延迟加载图片、视频或其他资源,直到它们接近或进入视口(用户可见的区域)。

这个组件库 能实现和 Intersection Observer一样的效果,而且使用非常方便,并且已经内置了加载逻辑,让代码看起来简洁很多

安装 vue3-lazyload

npm install vue3-lazyload

全局注册

<!--main.js-->
...
import Lazyload from "vue3-lazyload";

const app = createApp(App)

app.use(Lazyload, {
  loading: "@/assets/img/default.png",
  error: "@/assets/img/error.png",
});
...

使用完整案例

<template>
  <div class="image-container">
    <template v-for="(url, index) in images" :key="index">
      <img class="img" v-lazy="url" alt="图片" />
    </template>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const images = ref([
  "http://e.hiphotos.baidu.com/image/pic/item/a1ec08fa513d2697e542494057fbb2fb4316d81e.jpg",
  "http://c.hiphotos.baidu.com/image/pic/item/30adcbef76094b36de8a2fe5a1cc7cd98d109d99.jpg",
  "http://h.hiphotos.baidu.com/image/pic/item/7c1ed21b0ef41bd5f2c2a9e953da81cb39db3d1d.jpg",
  "http://g.hiphotos.baidu.com/image/pic/item/55e736d12f2eb938d5277fd5d0628535e5dd6f4a.jpg",
  "http://e.hiphotos.baidu.com/image/pic/item/4e4a20a4462309f7e41f5cfe760e0cf3d6cad6ee.jpg",
  "http://b.hiphotos.baidu.com/image/pic/item/9d82d158ccbf6c81b94575cfb93eb13533fa40a2.jpg",
  "http://e.hiphotos.baidu.com/image/pic/item/4bed2e738bd4b31c1badd5a685d6277f9e2ff81e.jpg",
  "http://g.hiphotos.baidu.com/image/pic/item/0d338744ebf81a4c87a3add4d52a6059252da61e.jpg",
  "http://a.hiphotos.baidu.com/image/pic/item/f2deb48f8c5494ee5080c8142ff5e0fe99257e19.jpg",
  "http://f.hiphotos.baidu.com/image/pic/item/4034970a304e251f503521f5a586c9177e3e53f9.jpg",
  "http://b.hiphotos.baidu.com/image/pic/item/279759ee3d6d55fbb3586c0168224f4a20a4dd7e.jpg",
  "http://a.hiphotos.baidu.com/image/pic/item/e824b899a9014c087eb617650e7b02087af4f464.jpg",
  "http://c.hiphotos.baidu.com/image/pic/item/9c16fdfaaf51f3de1e296fa390eef01f3b29795a.jpg",
  "http://d.hiphotos.baidu.com/image/pic/item/b58f8c5494eef01f119945cbe2fe9925bc317d2a.jpg",
  "http://h.hiphotos.baidu.com/image/pic/item/902397dda144ad340668b847d4a20cf430ad851e.jpg",
  "http://b.hiphotos.baidu.com/image/pic/item/359b033b5bb5c9ea5c0e3c23d139b6003bf3b374.jpg",
  "http://a.hiphotos.baidu.com/image/pic/item/8d5494eef01f3a292d2472199d25bc315d607c7c.jpg",
  "http://b.hiphotos.baidu.com/image/pic/item/e824b899a9014c08878b2c4c0e7b02087af4f4a3.jpg",
  "http://g.hiphotos.baidu.com/image/pic/item/6d81800a19d8bc3e770bd00d868ba61ea9d345f2.jpg",
]);


</script>

<style>
.image-container {
  width: 100%;
  overflow: hidden;
  overflow-y: scroll;
}

.img {
  width: 100%;
  height: 500px;
  display: block;
  margin-bottom: 20px;
  object-fit: cover;
}
</style>

如果您觉得这篇文章有帮助,请点个赞吧~

分享文章

相关文章

更多文章 →
javascript2026-02-24
navigator.sendBeacon全指南
在前端开发中,埋点系统是必不可少的一环。我们经常需要在用户 关闭页面 、 刷新 或 跳转路由 时,向服务器发送最后一条统计数据(比如用户停留时长、页面跳出率)。 但这看似简单的需求,在实现时却危机四伏:请求发不出去?页面跳转卡顿?今天我们就来聊聊这个问题的终极解决方案 —— 。 一、 痛点与传统方案的挣扎 场景还原 当用户点击关闭按钮时,浏览器会触发生命周期事件( 或 )。如果我们直接使用普通的异步 AJAX ( 或 ) 发送请求,浏览...
学习
javascript2025-11-02
理解浏览器事件系统,从用户点击到事件对象的完整旅程
深入理解浏览器事件系统:从用户点击到事件对象的完整旅程 “当我点击页面按钮时,背后发生了什么?为什么回调函数能收到一个包含丰富信息的event对象?今天,让我们一起揭开浏览器事件系统的神秘面纱。” 一个令人困惑的现象 作为前端开发者,我们每天都在写这样的代码: 这段代码如此熟悉,以至于我们很少停下来思考:​ ​这个 对象到底从哪里来?它为什么能知道点击的精确坐标?为什么能识别是哪个元素被点击了?​ ​ 更神奇的是,当我们手动创建事件时:...
学习
javascript2025-10-01
实现大文件上传全流程详解
在日常开发中,大文件上传是个绕不开的坎——动辄几百 MB 甚至 GB 级的文件,直接上传不仅容易超时,还会让用户体验大打折扣。最近我用 Vue+Express 实现了一套完整的大文件上传方案,支持分片上传、断点续传、秒传和手动中。 一、先看效果:我们要实现什么? 先上核心功能清单,确保大家明确目标,知道我们要解决哪些实际问题: 大文件分片上传 :将文件切成固定大小的小片段分批上传,避免单次请求超时 秒传 :服务器已存在完整文件时,直接返...
学习
javascript2025-09-18
JavaScript 的多线程能力:Worker
如果你写过一些计算量稍大的 JavaScript 代码,比如图像处理、大量数据排序或者复杂的算法,你几乎肯定遇到过浏览器“卡死”的现象。点击页面没反应,动画也停了,就像整个世界都静止了。 这就是主线程被阻塞的典型后果。因为主线程既要负责执行 JavaScript,又要负责渲染页面、响应用户操作,一旦它被繁重的计算任务占满,就无暇顾及其他,用户体验便直线下降。 这个问题的根源,正是“主线程是单线程的”。那么,如何解决呢? 答案很简单:把这...
学习面试
javascript2025-09-15
一张 8K 海报差点把首屏拖垮
你给后台管理系统加了一个「企业风采」模块,运营同学一口气上传了 200 张 8K 宣传海报。首屏直接飙到 8.3 s,LCP 红得发紫。 老板一句「能不能像朋友圈那样滑到哪看到哪?」——于是你把懒加载重新翻出来折腾了一轮。 解决方案:三条技术路线,你全踩了一遍 1\. 最偷懒:原生 一行代码就能跑,浏览器帮你搞定。 🔍 关键决策点 2020 年后现代浏览器全覆盖,IE 全军覆没。 必须写死 ,否则 CLS 会抖成 PPT。 适用场景...
学习
javascript2025-09-10
🚀 Web Worker让你的应用丝滑
🌟 引言 在日常的前端开发中,你是否遇到过这样的困扰: 大数据处理时页面卡死 :处理几万条数据时,页面直接卡成PPT,用户点击毫无反应 复杂计算阻塞UI :图片处理、数据分析等计算密集型任务让整个应用假死 文件上传/下载卡顿 :大文件操作时,其他功能完全无法使用 实时数据处理性能差 :WebSocket接收大量数据时,页面渲染严重滞后 今天分享6个Web Worker的核心技巧,让你的应用告别卡顿,用户体验丝滑如德芙! 💡 核心技巧...
学习

评论

请登录后发表评论

去登录
加载评论中...

目录