懶加載(lazyload)也叫延遲加載, 惰性加載. 實質是當網頁頁面滾動到相應的地方,對應位置的內容才進行加載顯示,這樣能明顯減小了服務器的壓力和流量,也可以減少瀏覽器的負擔,同時用戶也能更快開始網站的訪問javascript
通常狀況下, img標籤是這樣寫的css
<img src="..." alt="封面">複製代碼
懶加載約定俗成的寫法java
<img class="lazyload" data-src="${list.picUrl}" alt="封面">複製代碼
建立一個lazyload函數並調用它, 傳入圖片數組
lazyload(document.querySelectorAll('.lazyload'))複製代碼
初級版本瀏覽器
function lazyload(images){
let imgs = [].slice.call(images) // 將dom對象變成數組
window.addEventListener('scroll',onscroll) // 添加 scroll 事件監聽
window.dispatchEvent(new Event('scroll')) // 由於是監聽scroll,因此手動觸發保證第一屏的加載
function onscroll(){
if(imgs.length === 0){ // 若是沒有待加載圖片,移除監聽
return window.removeEventListener('scroll',onscroll)
}
mgs = imgs.filter(img => img.classList.contains('lazyload')) // 清洗數組
imgs.forEach(img => {
if(inViewport(img)){
loadImage(img)
} }) }
function inViewport(img){ // 判斷img元素是否在視口內
let {top,right,bottom,left} = img.getBoundingClientRect()
let vpHeight = document.documentElement.clientHeight
let vpWidth = document.documentElement.clientWidth
return (
(top > 0 && top < vpHeight || bottom> 0 && bottom < vpHeight)
&& (left > 0 && left < vpWidth || right > 0 && right < vpWidth) )}
function loadImage(img){ // img加載函數,加載後移除lazyload
let image = new Image()
image.src = img.dataset.src
image.onload = function(){
img.src = image.src
img.classList.remove('lazyload')
}
}}複製代碼
這個方法的問題在於scroll事件觸發太頻繁, 太影響瀏覽器性能bash
咱們能夠使用underscore.js 它提供了一個_.throttle方法服務器
<script src="https://cdn.bootcss.com/underscore.js/1.9.1/underscore-min.js"></script>複製代碼
若是傳入一個函數, 並在末尾設置時間, 該方法會返回一個新的函數, 且新函數的調用間隔爲設置的時間dom
let onscroll = _.throttle(fn() , 500);複製代碼
這樣scroll事件觸發間隔爲500秒, 能夠下降對瀏覽器性能的影響函數
接下來咱們試着本身寫一個throttle函數性能
function throttle(func,wait) {
let previous,timer
return function fn(){
let current = Date.now()
let different = current - previous
if(!previous || different >= wait){
func()
previous = current
}else if(different < wait){
clearTimeout(timer)
timer = setTimeout(fn,wait - different)
}
}
}複製代碼
調用方法和以前相同, 傳入一個函數和間隔時間