vue2实现图片懒加载
实现图片懒加载的方法
在Vue2中实现图片懒加载可以通过以下方法完成,核心原理是监听图片是否进入可视区域,再动态加载图片资源。
使用IntersectionObserver API
IntersectionObserver是现代浏览器提供的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="'https://example.com/image.jpg'" alt="lazy image">
使用自定义滚动事件监听
对于不支持IntersectionObserver的旧浏览器,可通过scroll事件实现:
Vue.directive('lazy', {
inserted: (el, binding) => {
function checkInView() {
const rect = el.getBoundingClientRect()
return (
rect.top < window.innerHeight &&
rect.bottom > 0
)
}
function loadImage() {
if (checkInView()) {
el.src = binding.value
window.removeEventListener('scroll', loadImage)
}
}
window.addEventListener('scroll', loadImage)
loadImage() // 初始检查
}
})
使用第三方库
vue-lazyload是成熟的懒加载库,提供更多功能:

安装:
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="'image.png'" alt="">
性能优化建议
- 添加占位图避免布局抖动
- 设置threshold参数提前加载
- 对滚动事件进行节流处理
- 组件销毁时移除事件监听
- 考虑兼容性时提供polyfill
通过以上方法可以实现高效的图片懒加载,显著提升页面性能。根据项目需求选择原生实现或第三方库方案。






