如何在 Vue 中实现图片的 IntersectionObserver 懒加载?

解读

国内业务对首屏性能与 SEO 评分越来越敏感,面试官问“懒加载”并不是想听“用第三方库”一句话,而是想确认候选人能否:

  1. 手写一个无依赖、可复用的 Vue 指令;
  2. 正确处理 SSR 与客户端 hydration 差异;
  3. 兼顾内存泄漏、降级、加载失败重试、骨架屏等工程细节;
  4. 在 Vue3 Composition API 与 <script setup> 语法糖下给出符合官方推荐范式的代码。

一句话:要体现“能直接上线”的严谨程度。

知识点

  • IntersectionObserver 基本用法、rootMargin/threshold 语义
  • 指令生命周期(mounted、unmounted)与 vnode 绑定
  • 图片解码 decode() 与 requestAnimationFrame 优化
  • 占位图/骨架屏与 transition 动画衔接
  • WeakMap 缓存 observer 实例,防止内存泄漏
  • 服务端渲染时跳过 observer,客户端 hydration 后延迟注册
  • 加载失败重试策略(最多 3 次,指数退避)
  • 性能指标:LCP(最大内容绘制)与 CLS(累积布局偏移)优化
  • Vue3 自定义指令在 <script setup> 中的注册方式(vImgLazy)
  • 与 Vite 的 import.meta.glob('@/assets/img/**/*.{png,jpg}') 结合做静态资源哈希映射

答案

  1. 设计无依赖的自定义指令 v-img-lazy
// directives/imgLazy.js
const ioMap = new WeakMap();          // 节点 -> observer 映射
const retryMap = new WeakMap();       // 节点 -> 重试次数

function loadImage(el, src, binding) {
  const img = new Image();
  img.src = src;
  img.decode()
    .then(() => {
      el.src = src;
      el.classList.add('loaded');
      binding.instance?.$emit('lazyLoaded', { el, src });
    })
    .catch(() => {
      const times = retryMap.get(el) || 0;
      if (times < 3) {
        retryMap.set(el, times + 1);
        setTimeout(() => loadImage(el, src, binding), 200 * (times + 1));
      } else {
        el.classList.add('error');
        binding.instance?.$emit('lazyError', { el, src });
      }
    });
}

function createObserver(el, binding) {
  if (typeof window === 'undefined') return; // SSR 环境直接返回
  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const src = binding.value;
          loadImage(el, src, binding);
          observer.unobserve(el);
          ioMap.delete(el);
        }
      });
    },
    { rootMargin: '100px', threshold: 0.01 }
  );
  observer.observe(el);
  ioMap.set(el, observer);
}

export default {
  mounted(el, binding) {
    el.classList.add('skeleton');      // 骨架屏样式
    createObserver(el, binding);
  },
  unmounted(el) {
    const ob = ioMap.get(el);
    if (ob) {
      ob.disconnect();
      ioMap.delete(el);
    }
    retryMap.delete(el);
  }
};
  1. 全局注册(main.js)
import { createApp } from 'vue';
import App from './App.vue';
import imgLazy from '@/directives/imgLazy';

const app = createApp(App);
app.directive('imgLazy', imgLazy);
app.mount('#app');
  1. 组件内使用
<template>
  <div class="waterfall">
    <img
      v-for="item in list"
      :key="item.id"
      v-img-lazy="item.url"
      class="photo"
      @lazyLoaded="onLoaded"
      @lazyError="onError"
    />
  </div>
</template>

<script setup>
const list = ref(await fetchList());   // 服务端预取
function onLoaded(e) { /* 埋点 */ }
function onError(e) { e.target.src = '/default.png'; }
</script>

<style>
.skeleton{ background:#f0f0f0; background-image:linear-gradient(90deg,#f0f0f0 25%,#e0e0e0 50%,#f0f0f0 75%); background-size:200% 100%; animation:shine 1.2s ease infinite; }
.loaded{ transition:opacity .3s; opacity:1; }
.error{ opacity:.3; filter:grayscale(100%); }
@keyframes shine{ 0%{background-position:-200% 0} 100%{background-position:200% 0} }
</style>
  1. 打包优化
  • 利用 Vite 的 import.meta.glob 把占位图也做哈希化,避免额外请求
  • 图片统一放 assets/img,构建后自动输出 WebP,并生成 srcset,指令内部判断支持情况动态赋值

拓展思考

  1. 如果项目需要兼容 IE11,IntersectionObserver 需加官方 polyfill,但 polyfill 性能差,可降级为 scroll + throttle 实现,并在指令内部做能力检测,避免把 polyfill 打给所有用户。
  2. 列表翻页时,旧节点被复用,指令会重复创建 observer;可在 updated 钩子中对比 binding.value 是否变化,若 url 不变则直接返回,减少开销。
  3. 骨架屏 CLS 抖动问题:给 img 固定宽高比(padding-top 百分比)或使用 aspect-ratio 属性,让占位尺寸与真实图片一致,布局分数直接降到 0。
  4. 与 Pinia 结合:把“已加载 URL”存到全局 Set,跳转到新路由后优先从内存缓存读取,秒开二屏。
  5. 微前端场景:子应用卸载时主应用可能把 DOM 一起移除,但 observer 仍在内存;务必在 unmounted 里 disconnect,并在主应用沙箱销毁钩子中再检查一次,防止泄漏。
  6. 监控:在 loadImage 成功回调里打 performance.mark,结合 performance.measure 上报 FCP-LCP 差值,量化懒加载带来的真实收益,面试时可直接说“我通过懒加载把 LCP 从 2.8 s 降到 1.9 s”,数字最有说服力。