WeChat applet image lazy loading implementation

Hits: 0

Realize ideas

First, set up an [array] to be false, and compare the height of the picture with the height of the screen scrolling. When this point is reached, the corresponding false in the array becomes true. When the false of the array becomes true, we can display the image. Of course, first we need to judge how many pictures the first screen can hold, and then display them. code show as below:

wxml page code

<view class = "shoplist_text" wx: for = "{{yylist}}" wx:key= "{{index}}" bindtap= "to" data-id= "{{item.id}}" >
  /* "item.pic" real data*/          /* "item.pic" : a colon followed by an image to set lazy loading */ 
        < image   src = "{{arry[index] ? item.pic: 'https://dss1. bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=278371386,196634131&fm=26&gp=0.jpg'}}"  class = "{{arry[index] ?'Action':''}}" > </ image > 
 </view>

js page code

data: {
     damoHeight : '150' , //demo height 
    arry: [ false ], //The image is not displayed by default when lazy loading
  },

  //Get the scrolling distance 
  onPageScroll: function ( res ) {
     console .log(res)
     var _this = this ;
     var str = parseInt (res.scrollTop / _this.data.damoHeight);
    _this.data.arry[str] = true;
    _this.setData({
      arry: _this.data.arry
    })
  },
  onLoad: function () {
     //Image lazy loading 
    let _this = this ;
     let num = Math .ceil(wx.getSystemInfoSync().windowHeight / 300 );
     for ( let i = 0 ; i < num; i++) {
      _this.data.arry[i] = true;
    };
    this.setData({
      arry: _this.data.arry
    })
}

wxss page code

image {
  opacity: 0;
  width: 100%;
  height: 300px;
  transition: opacity 0.4s linear 0.4s;
}

.Action {
  opacity: 1;
}

You may also like...

Leave a Reply

Your email address will not be published.