小程序对用户内存使用进行了限制,若是一个页面的图片过多,会致使内存不足的内部错误
对图片进行懒加载,不影响体验的前提下,只渲染当屏的图片,屏外图片,显示缺省图
图片最多的状况就是列表(头图或图片列表),为了性能,通常会滚动加载,而在小程序中,须要借助scroll-view/swiper组件,为了避免影响用户体验,就不能让以前以渲染的列表元素失去占位小程序
要判断元素是否在当屏,就要知道一些高度信息(屏幕高,滚动高度,元素高度),可是元素高度在小程序中不能动态获取,因此就须要列表时定高的ide
wxml文件性能
<!-- showIndex为当屏中首列表元素的索引值 scrollLoad滚动加载 scrollHide图片当屏渲染 --> <scroll-view wx:if="{{isNet}}" scroll-y="true" bindscrolltolower="scrollLoad" bindscroll="scrollHide"> <view wx:if="{{total}}"> <block wx:for="{{imgDatas}}"> <view> <image wx:if="{{showIndex + 24 > index && showIndex - 6 < index}}" src="{{item.pic.url}}" mode="aspectFill"></image> </view> </block> </view> </scroll-view>
计算showIndex的方法,可做为公用方法ui
/** * offetHeight 滚动计算部分到顶部距离 * scrollTop 滚动高度 * height 每一个模块的高度 * colunm 列数 **/ function countIndex (offetHight, scrollTop, height, colunm) { // 单例获取屏幕宽度比 if (!countIndex.pix) { try { let res = wx.getSystemInfoSync() countIndex.pix = res.windowWidth / 375 } catch (e) { countIndex.pix = 1 } } let scroll = scrollTop - offetHight * countIndex.pix let hei = height * countIndex.pix return scroll > 0 ? Math.floor(scroll / hei) * colunm : 0 }
js文件this
let wxTools = require('../../untils/wxTools.js') Page({ data: { scrollData: { offetHeight: 15, // px height: 80, // px colunm: 3 }, showIndex: 0 }, scrollHide (e) { let data = [ this.data.scrollData.offetHeight, e.detail.scrollTop, this.data.scrollData.height, this.data.scrollData.colunm ] let index = wxTools.countIndex(...data) this.setData({ showIndex: index }) } })
具体要渲染多少的元素,本身来定,这里没有放到countIndex中加入计算,例如wxml中的{{showIndex + 24 > index && showIndex - 6 < index}},会渲染30个元素的图片url