微信小程序封装懒加载图片
js
/components/Watermark/index.js
Component({
properties: {
src: {
type: String,
value: 'https://s1.ax1x.com/2022/05/08/OlbiFI.gif'
},
lazyImageUrl: {
type: String,
value: 'https://s1.ax1x.com/2022/05/08/OlbiFI.gif'
},
alt: {
type: String,
value: ''
},
mode: {
type: String,
value: 'widthFix'
},
},
data: {
imageId: ""
},
lifetimes: {
async ready() {
const imageId = 'image' + Date.now();
this.setData({
imageId
});
this.lazy('.' + imageId);
}
},
methods: {
lazy(className) {
const IntersectionObserver = this.createIntersectionObserver();
IntersectionObserver.relativeToViewport();
IntersectionObserver.observe(className, async (res) => {
if (res.intersectionRatio) {
this.setData({
lazyImageUrl: this.data.src
});
IntersectionObserver.disconnect();
}
})
},
}
})
wxml
/components/Watermark/index.wxml
<view>
<image src="{{lazyImageUrl}}" mode="{{mode}}" alt="{{alt}}" class="lazy-image {{imageId}}">
</image>
</view>
wxss
.lazy-image {
display: block;
width: 100%;
}
组件已经发布到npm,移步查看wmp-lazy-image
|