微信小程序实现图片懒加载(vue2版)

微信小程序实现图片懒加载(vue2版)
### 1、为什么需要懒加载 如果大量图片在同一个时间点全部加载会使得加载速度变慢,并且服务器的压力也会增大,这时候就需要==懒加载==了,所谓的懒加载就是在图片需要加载时加载时加载,我们可以定义当图片全部出现在视窗中时图片在加载。 ### 2、前端代码 ```html <image class="item-image" id="image-{{idx}}" src="{{item.fileurl || '../../images/shijian_pic_empty_da.png'}}" mode="aspectFill" bindtap="show" data-id="{{idx}}" onload="loadImages" ></image> ``` ### 3、后端代码 ```js loadImages: function(e) { if(!e)return; const idx = e.currentTarget.dataset.id; for (let i = 0; i < this.data.list.length; i++) { if (idx !== i) continue; const intersectionObserver = wx.createIntersectionObserver(this, { thresholds: [1] }); intersectionObserver.relativeToViewport({ bottom: 0 }).observe(`#image-${i}`, (res) => { if (res.intersectionRatio > 0) { // 图片进入可视区域,加载图片 this.setData({ [`list[${i}].fileurl`]: this.data.list[i].realUrl }); } }); } }, ``` 当==image==标签加载完后执行==onload==,==e.currentTarget.dataset.id==获取当前标签,设置==thresholds: [1]== 即图片全部在窗口,将src替换为真实图片地址,否则为静态预览图片。