虽然微信小程序自己的image组件中有懒加载属性,但是根据文档的说明:image组件的lazy-load懒加载属性将在图片在即将进入一定范围(上下三屏)时才开始加载。感觉懒加载效果不怎么明显。那这次将用另外一种方法来实现图片的懒加载。
1.相关的API
IntersectionObserver 对象,用于推断某些节点是否可以被用户看见、有多大比例可以被用户看见。
其中有一个API,用于监听指定对象与显示区域为参照区域的相交状态变化情况:IntersectionObserver.relativeToViewport(Object margins),简洁的说明就是:指定某个对象,如果该对象在滚动的时候出现在显示区域(与显示区域相交),则调用方法。
2.布局
<template>
<view class='bg_div'>
<view class="ball">
<image src="../images/bar_1.png" wx:if="{{isShow}}" />
</view>
</view>
</template>
<style lang='scss'>
.bg_div{
width:100%;
height:300%;
display:flex;
justify-content:center;
align-items:center;
.ball{
width:300rpx;
height:300rpx;
border-radius:150rpx;
background:#f5f5f5;
display:flex;
justify-content:center;
align-items:center;
image{
width:70rpx;
height:70rpx;
}
}
}
</style>
根据这个布局,现在只需要控制isShow,未在显示区域事isShow为false,在class为ball的这个view,即将滚动到显示区域的赋值为true,就能实现懒加载。因此,可以使用方法:IntersectionObserver.relativeToViewport(Object margins)来监听.ball与显示区域的相交情况来实现。
3.加载监听方法
<script>
import wepy from 'wepy'
export default class FirstPage extends wepy.page{
data = {
isShow:false
}
onLoad(){
this.lazyLoad();
}
lazyLoad(){
wx.createIntersectionObserver().relativeToViewport({bottom:0}).observe('.ball',(ret)=>{
if(ret.intersectionRatio > 0){
this.isShow = true;
console.log('显示',ret.intersectionRatio);
}
this.$apply();
});
}
}
</script>
在页面加载时创建监听,监听ball与显示区域的相交情况,当相交的时候,会调用方法。(默认创建的IntersectionObserver 对象实例的属性,阈值为0,相当于相交比例达到该阈值时将调用方法),因此当ball将要显示时(与显示区域相交),将isShow赋值为true,那图片将显示,因此实现图片的懒加载。