在微信小程序中,實現圖片懶加載的方式有不少html
實現思路小程序
image
標籤裏的lazy-load
屬性Intersection Observer API
鑑於第一種方式目前看不出效果,第二種方式代碼量仍是有點大的,咱們在這裏用第三種方式來實現圖片懶加載。微信小程序
WXML
節點佈局相交狀態api
<scroll-view>
<view class="image-panel item item-{{index}}" wx:for="{{list}}" wx:for-item="item" wx:key="{{index}}">
<view class="video-play" bindtap="linkToDetail">
<image class="{{item.show ? 'active': ''}}" src="{{item.show ? item.cover : default}}" mode="widthFix" lazy-load />
</view>
</view>
</scroll-view>
複製代碼
注意bash
image
標籤里加上了lazy-load
屬性,要配合scroll-view
使用纔有效果。惋惜,在本地沒有測出效果。show
這個字段來判斷是否顯示原圖,未加載的狀況下使用默認圖來展現。const url = "";//業務api地址
const that = this;
const obj = {
method: 'get',
url: url,
success: function (res) {
var items = res.data.items;
that.setData({
list: items
})
setTimeout(() => {
for (let i in res.data.items) {
wx.createIntersectionObserver().relativeToViewport({bottom: 20}).observe('.item-' + i, (res) => {
if (res.intersectionRatio > 0) {
items[i].show = true
}
that.setData({
list: items
})
})
}
}, 1*1000);
}
}
common.httpRequest(obj)
複製代碼
注意微信
createIntersectionObserver()
方法微信小程序官方文檔ide