在普通的web頁面當中,我們都知道圖片懶加載可以提升瀏覽器的加載速度。原理是圖片用空或者占位圖片進行顯示,當屏幕移動到圖片位置的時候,再把圖片的地址換成它的地址。那么,在小程序當中呢,最近老大讓看一下微信小程序的優化方面,圖片是很吃資源的一項,所以我把矛頭指向了懶加載:
首先寫代碼之前一定要理清楚思路,我想的基礎是懶加載的思路,首先設立一個數組都為false,讓圖片的高度和屏幕滾動的高度進行比較,當到達這個點的時候,數組里面對應的false變成true。當數組的false變成true的時候,我們讓圖片進行顯示就可以啦。當然,首先我們需要判斷一下首屏能容納多少個圖片,然后把他們顯示出來。好,上代碼:
.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高度 imgUrls: [//圖片地址 { 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 }) } })
不會的可以加博主進行一起探究