How to achieve image lazy loading in UniApp?
To achieve image lazy loading, you can use the IntersectionObserver component provided by uniapp. Here are the steps to implement image lazy loading:
- Create an IntersectionObserver object in Uniapp to observe if an image enters the visible area.
// 在页面的onLoad钩子函数中创建IntersectionObserver对象
onLoad() {
this.observer = uni.createIntersectionObserver(this)
}
- Bind an IntersectionObserver object to the image tag on the page, and set the initial src of the image to a placeholder.
<template>
<img :src="placeholder" :data-src="imageUrl" @load="onImgLoad" class="lazy-img">
</template>
- Listen to the IntersectionObserver object’s callback function, when the image enters the visible area, assign the value of the data-src attribute to the src attribute, achieving lazy loading of the image.
// 在页面的onReady钩子函数中开始观察图片
onReady() {
this.observer
.relativeToViewport()
.observe('.lazy-img', (res) => {
if (res.intersectionRatio > 0) {
const { dataset } = res.target
res.target.src = dataset.src
this.observer.disconnect()
}
})
}
- Assign the src attribute of the image to the actual image link when the image finishes loading.
methods: {
onImgLoad(event) {
const { dataset } = event.target
event.target.src = dataset.src
}
}
In this way, when the image enters the visible area, the src attribute of the image will be replaced with the actual image link, achieving lazy loading of images.