uniapp实现懒加载
uniapp实现懒加载的方法
在uniapp中实现懒加载可以通过多种方式,以下是几种常见的方法:
使用uni.lazyLoad组件
uniapp提供了内置的懒加载组件,适用于图片等资源的懒加载。在页面中引入并使用该组件:
<uni-lazy-load>
<image v-for="item in list" :key="item.id" :src="item.url" lazy-load></image>
</uni-lazy-load>
需要在pages.json中配置懒加载选项:
{
"lazyLoad": {
"enable": true,
"loadingImg": "/static/loading.png",
"errorImg": "/static/error.png"
}
}
使用Intersection Observer API
通过监听元素是否进入视口来实现懒加载:

const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target
img.src = img.dataset.src
observer.unobserve(img)
}
})
})
document.querySelectorAll('img[data-src]').forEach(img => {
observer.observe(img)
})
使用第三方库
可以引入第三方懒加载库如vue-lazyload:
安装依赖:

npm install vue-lazyload --save
在main.js中配置:
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload, {
preLoad: 1.3,
error: 'static/error.png',
loading: 'static/loading.gif',
attempt: 1
})
在组件中使用:
<img v-lazy="imgUrl">
自定义懒加载逻辑
通过监听页面滚动事件,计算元素位置实现懒加载:
onPageScroll(e) {
const query = uni.createSelectorQuery()
query.selectAll('.lazy-item').boundingClientRect(rects => {
rects.forEach(rect => {
if (rect.top < window.innerHeight + 100) {
// 加载内容
}
})
}).exec()
}
注意事项
- 懒加载需要配合合理的占位图,避免页面布局抖动
- 移动端需要考虑滚动性能优化
- 对于长列表,建议结合虚拟滚动技术
- 图片懒加载需要注意图片尺寸的提前设定,避免重排
以上方法可以根据具体需求选择使用,通常推荐使用uniapp内置的懒加载组件或Intersection Observer API实现。






