当前位置:首页 > VUE

vue2实现图片懒加载

2026-01-07 06:24:18VUE

Vue2 图片懒加载实现方法

使用 Intersection Observer API

Intersection Observer API 是浏览器原生支持的懒加载方案,性能较好且无需额外库。

// 全局指令或在组件中定义
Vue.directive('lazy', {
  inserted: (el, binding) => {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          el.src = binding.value
          observer.unobserve(el)
        }
      })
    })
    observer.observe(el)
  }
})

模板中使用方式:

<img v-lazy="imageUrl" alt="description">

使用 vue-lazyload 插件

vue-lazyload 是 Vue 生态中成熟的懒加载解决方案。

安装依赖:

npm install vue-lazyload

全局配置:

import VueLazyload from 'vue-lazyload'

Vue.use(VueLazyload, {
  preLoad: 1.3,
  error: 'error.png',
  loading: 'loading.gif',
  attempt: 3
})

模板中使用:

<img v-lazy="imageUrl" alt="description">

自定义滚动事件监听

适用于需要兼容旧浏览器的场景。

Vue.directive('lazy', {
  inserted: (el, binding) => {
    function checkVisible() {
      const rect = el.getBoundingClientRect()
      return (rect.top <= window.innerHeight && rect.bottom >= 0)
    }

    function loadImage() {
      if (checkVisible()) {
        el.src = binding.value
        window.removeEventListener('scroll', loadImage)
      }
    }

    window.addEventListener('scroll', loadImage)
    loadImage() // 初始检查
  }
})

注意事项

  • 图片需要设置固定宽高或使用 CSS 保持占位,避免页面抖动
  • 移动端建议增加 200-300px 的提前加载距离
  • 对于重要图片可添加 noscript 标签作为降级方案
  • 大量图片时建议配合节流(throttle)函数优化性能

性能优化建议

  • 使用低质量图片占位符(LQIP)技术
  • 响应式图片配合 srcset 属性
  • 对已加载图片进行缓存
  • 对离开视口的图片进行资源释放

vue2实现图片懒加载

标签: 加载图片
分享给朋友:

相关文章

vue 实现异步加载

vue 实现异步加载

Vue 实现异步加载的方法 使用动态 import 实现组件懒加载 在 Vue 中可以通过动态 import() 语法实现组件的异步加载,这会使得组件在需要时才被加载,减少初始加载时间。 cons…

vue实现图片轮播

vue实现图片轮播

Vue 实现图片轮播的方法 使用第三方库(推荐) 安装 vue-awesome-swiper 库,这是基于 Swiper 的 Vue 封装: npm install swiper vue-awe…

vue2实现图片懒加载

vue2实现图片懒加载

实现图片懒加载的方法 在Vue2中实现图片懒加载可以通过以下方法完成,核心原理是监听图片是否进入可视区域,再动态加载图片资源。 使用IntersectionObserver API Interse…

js实现图片预览

js实现图片预览

使用FileReader API实现图片预览 通过FileReader对象读取用户选择的图片文件并显示预览: const input = document.getElementById('imag…

js实现图片放大缩小

js实现图片放大缩小

实现图片放大缩小的基础方法 使用CSS的transform: scale()属性可以快速实现图片的放大缩小效果。通过JavaScript动态修改该属性值: const img = document.…

h5实现全景图片

h5实现全景图片

H5 实现全景图片的方法 使用 Three.js 库 Three.js 是一个强大的 3D 库,可以用于创建全景图片效果。以下是一个简单的实现步骤: 引入 Three.js 库 <sc…