vue2实现图片懒加载
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 属性
- 对已加载图片进行缓存
- 对离开视口的图片进行资源释放







