在微信小程序中,实现图片懒加载的方式有不少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