小程序图片懒加载


<view>
  <view>
    <view wx:for="{{img}}" class="item-{{index}}" wx:key="index">
      <view wx:if="{{index < count}}">
        <image  src="{{item}}">image>
      view>
    view>
  view>
view>

JS脚本部分处理:

//index.js
//获取应用实例
const app = getApp()
let lazyload;

Page({
  data: {
    classNote: '.item-', //循环节点前缀
    count: 0, //总共加载到多少张
    img: [
      'https://js.pic88.com/upload/2020820/15979098400907496221',
      'https://js.pic88.com/upload/2020820/15979098400907496221',
      'https://js.pic88.com/upload/2020820/15979098400907496221',
      'https://js.pic88.com/upload/2020820/15979098400907496221',
      'https://js.pic88.com/upload/2020820/15979098400907496221',
      'https://js.pic88.com/upload/2020820/15979098400907496221',
      'https://img.pic88.com/preview/2020/08/05/15966339461452544.jpg!s640w',
      'https://js.pic88.com/upload/2020820/15979098400907496221',
      'https://js.pic88.com/upload/2020820/15979098400907496221',
      'https://js.pic88.com/upload/2020820/15979098400907496221',
      'https://img.pic88.com/preview/2020/08/05/15966339251452714.jpg!s640w',
    ]
  },
  onReady: function () {
    //可以先初始化首屏需要展示的图片
    this.setData({
      count: 5
    })
    //开始监听节点,注意需要在onReady才能监听,此时节点才渲染
    this.viewPort()
  },
  viewPort: function () {
    if ((this.data.count > this.data.img.length) || !wx.createIntersectionObserver) {
      // 超出了范围不要再监听了或者根本就API不支持
      return this.data.count = this.data.img.length
    }
    const intersectionObserver = wx.createIntersectionObserver();
    //这里bottom:100,是指显示区域以下 100px 时,就会触发回调函数。
    intersectionObserver.relativeToViewport().observe(this.data.classNote + (this.data.count - 1), (res) => {
      if (res.boundingClientRect.top > 0) {
        intersectionObserver.disconnect()
        this.setData({
          count: this.data.count + 5
        })
        this.viewPort();
      }
    })
  }
})

这里有2点需要注意的:

监听的节点需要先渲染,也就是说监听这个动作需要在onReady的时候
上述示例监听是依赖循环节点的class,最少需要先渲染一个节点才能监听
每次监听完一个循环节点后,结束监听,然后继续监听下一个节点

你可能感兴趣的:(JavaScript,小程序)