有時一個頁面中有多個圖片或視頻要展現,若是所有將資源加載顯示,會致使頁面暫時空白,用戶體驗很很差,要改變這種體驗的一種思路是先用一個佔位圖片顯示,而後在可視窗口展現的內容提早加載,保證用戶看到的是已經加載好的圖片等其餘佔用空間較大的資源.
例如:css
//css代碼: div image[alt^='picture'] { width: 100px; height: 100px; background: silver; } .img { height: 200px; width: 400px; } //html代碼 <div id="div" style='width:400px;height:1024px'> <image class="img" src="./time.gif" alt="picture1" data-src="./1.jpg" /> <image class="img" src="./time.gif" alt="picture2" data-src="./2.jpg" /> <image class="img" src="./time.gif" alt="picture3" data-src="./3.jpg" /> <image class="img" src="./time.gif" alt="picture4" data-src="./1.jpg" /> <image class="img" src="./time.gif" alt="picture5" data-src="./2.jpg" /> <image class="img" src="./time.gif" alt="picture6" data-src="./3.jpg" /> </div> //js代碼 var imgArr = document.getElementsByClassName('img'); var imgHeight = imgArr[0].style.height; var clientHeight = document.documentElement.clientHeight;//獲取網頁可見區域高度 window.onscroll = function() { var scrollTop = document.documentElement.scrollTop;//網頁垂直方向滾動的高度 for (let i = 0; i < imgArr.length; i++) { var offset = imgArr[i].offsetTop;//獲取當前對象到其上級層頂部的距離 var topT = scrollTop - ('200' + offset); var topB = scrollTop + clientHeight - offset; if (topT < 0 && topB > 0) { imgArr[i].src = imgArr[i].getAttribute('data-src'); } else { imgArr[i].src = './time.gif'; } } }
頁面剛開始以下圖所示,html
當滾動鼠標時,圖片陸續顯示 小程序
微信小程序是監聽目標節點和參照區域相交的狀態來實現懶加載微信小程序
//wxml代碼: <view> <view>懶加載示例</view> <view class="img-contain" wx:for="{{imgArr}}" wx:key="*this" wx:for-item="item" wx:for-index="index"> <image class="img" src="{{item.src}}" data-src="{{item.realSrc}}"> </image> <view class="img-title">{{item.title}}</view> </view> </view> //js代碼: Page({ data: { imgArr: [{ title: 'picture1', src: '../../images/timg.gif', realSrc: '../../images/1.jpg' }, { title: 'picture2', src: '../../images/timg.gif', realSrc: '../../images/2.jpg' }, { title: 'picture3', src: '../../images/timg.gif', realSrc: '../../images/3.jpg' }, { title: 'picture4', src: '../../images/timg.gif', realSrc: '../../images/4.jpg' } ] }, onLoad(options) { var _self = this; var obs = wx.createIntersectionObserver(this, { observeAll: true }); obs.relativeToViewport({ bottom: 100 }).observe('.img', function(res) { _self.data.imgArr.forEach(function(item) { if (res.dataset.src == item.realSrc) { if (res.intersectionRatio > 0) { item.src = res.dataset.src; } else { item.src = '../../images/timg.gif'; } _self.setData({ imgArr: _self.data.imgArr }); } }) }) }, })
如圖所示:
微信