关键点及整体思路:这里用的小程序的获取节点信息的apiwx.createSelectorQuery(),获取到用户手机系统的高度,通过判断节点的top小于手机系统的高度用来确定页面的内容是否在显示的区域里,然后实现懒加载效果。
1.wxml页面
<image class = "img {{item.showImg? 'active':'image'}}" wx:for = '{{img}}'
mode = 'widthFix' src="{{item.showImg ? item.src:item.lazy }}"
wx:key='index'
id= 'img'></image>
这里通过判断item.showImf为true或false的方式判断图片显示具体内容还是省略图
2.js文件
onLoad: function (options) {
var me = this;
wx.getSystemInfo({
success: res => {
me.data.height = res.screenHeight
}
})
},
onReady: function () {
let imglist = this.data.img
var me = this
wx.createSelectorQuery().selectAll('#img').boundingClientRect(img => {
img.map((item, index) => {//通过节点选择器获取到id img标签的内容并且绑定了事件
if (item.top <= me.data.height) {//通过判断判断节点的高度是否小于视图区域动态添加showImg属性
imglist[index].showImg = true
} else {
imglist[index].showImg = false
}
if (item.bottom == 0) {
///因为我的页面效果是三张图片并排显示,为了避免最后一排图片没有效果所以这里判断当是最后一组图片的时候修改其属性
imglist[length - 1].showImg = true
imglist[length - 2].showImg = true
imglist[length - 3].showImg = true
}
me.setData({
img: imglist
})
})
}).exec()
},
3.然后在onPageScroll生命周期函数中调用该方法
onPageScroll(e){
this.onReady()
},
总结:网上实现图片懒加载的方式用到了wx.createIntersectionObserver()通过判断intersectionRatio的数值判断是否在显示区域(当在显示区域的时候intersectionRatio等于1,隐藏区域时小于1的方式来动态添加属性 在页面中判断是否显示,但是弊端通过循环判断条件,当条件符合的时候就setData一次这样反而适得其反,导致性能变差,好的方法可以封装promise,当resolve返回最终动态添加完属性的内容 一次setData即可,并要配合节流函数一起使用,但是整体效果和性能还是不如第一种方法,但我们可以依旧使用wx.createIntersectionObserver实现项目中其他的效果)