Wechat applet pictures lazy loading

In ordinary web pages, we all know that lazy loading of images can improve the loading speed of the browser. The principle is that the picture is displayed with an empty or placeholder picture. When the screen moves to the picture position, the address of the picture is replaced with its address. Well, in the applet, the boss recently asked him to take a look at the optimization of the WeChat applet. Pictures are a resource-intensive item, so I pointed the finger at lazy loading:

First of all, you must clarify your ideas before writing the code. The basis of my thinking is the idea of ​​lazy loading. First, set up an array to be false, so that the height of the image is compared with the height of the screen scrolling. When this point is reached, the corresponding array in the array corresponds to false 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. OK, the code above:

.wxml:

<!--pages/test/test.wxml-->
<view>
   <image wx:for="{{imgUrls}}" wx:key="item" src="{{arry[index] ? imgUrls[index].url: './../../img/index.gif'}}" class="{{arry[index] ?'Action':''}}"></image>
</view>

 .wxss:

 

/* pages/test/test.wxss */

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

.Action {
  opacity: 1;
}

  .js:

Page({
  data: {
    damoHeight: '150', // demo altitude
    imgUrls: [//image address
      {
        url: 'http://g.ydbcdn.com/site/imgs/1.png'
      }, {
        url: 'http://g.ydbcdn.com/site/imgs/2.png'
      },
      {
        url: 'http://g.ydbcdn.com/site/imgs/3.png'
      }, {
        url: 'http://g.ydbcdn.com/site/imgs/4.png'
      }
    ],
    arry: [false, false, false, false],

  },
  onPageScroll: function (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 () {
    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
    })
  }
})

  If not, you can add bloggers to explore together

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324791512&siteId=291194637