小程序對用戶內存使用進行了限制,若是一個頁面的圖片過多,會致使內存不足的內部錯誤
對圖片進行懶加載,不影響體驗的前提下,只渲染當屏的圖片,屏外圖片,顯示缺省圖
圖片最多的狀況就是列表(頭圖或圖片列表),爲了性能,通常會滾動加載,而在小程序中,須要藉助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