微信小程序 懒加载

微信小程序 懒加载

1.需要使用到 wx小程序中的 createIntersectionObserver , relativeToViewport ,observe 等一系列 API ,API使用方法详情 官网: https://developers.weixin.qq.com/miniprogram/dev/api/wxml/wx.createIntersectionObserver.html

2.实践:

// index.wxml
<view class="lazy-{{index}}"  wx:for="{{newsLists}}"  wx:key="index" >
	<image src="{{item.show ? item.src:loadingIcon }}"></image>	
</view>

//index.js
page({
	data:{
		newsLists:[
			{
				src:'图片src',
				show:false, //用于判断图片是否加载
			},
			...
		],
		loadingIcon:'加载中的gif图片/缓冲过渡图片 地址'
	},
	onLoad:function(){
		
	},
	lazyImage(){
		const newsLists = this.data.newsLists;
		for(let index in newsLists){
			wx.createIntersectionObserver().relativeToViewport({
			     bottom: 20     // 到达 距离该元素底部 20px 时触发
			   }).observe(`.lazy-${index}`, (ret) => {   // 选择出进行监听的元素  以及触发的 处理回调函数
			    ret.intersectionRatio > 0 ? newsLists[index].show = true : ''; //此处将  show属性改为true 使图片正常加载 显示
				this.setData({
					newsLists:newsLists  //更新data内的数据
				});			
			})
		}
	},
})
发布了96 篇原创文章 · 获赞 64 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_41709082/article/details/104430635
今日推荐