vue2实现图片懒加载
Vue2 实现图片懒加载的方法
使用 Intersection Observer API
Intersection Observer API 是浏览器原生支持的懒加载方案,性能高效且不依赖第三方库。
// 在 main.js 或组件中注册自定义指令
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="lazy image">
使用 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="lazy image">
滚动事件监听实现
对于需要兼容老浏览器的场景,可以使用传统滚动监听方式。
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() // 初始检查
}
})
注意事项
- 图片元素应设置初始占位图或背景色
- 考虑添加加载中和加载失败的占位状态
- 移动端需要处理视口缩放情况
- 大量图片时注意性能优化和内存管理
性能优化建议
- 结合 requestIdleCallback 实现空闲时加载
- 对离屏图片设置适当延迟
- 使用 data-src 代替直接修改 src 属性
- 考虑图片尺寸自适应需求






