本文實例講述了JavaScript實現圖片懶加載的方法。分享給大家供大家參考,具體如下:
懶加載是非常實用的提升網頁性能的方式,當訪問一個頁面的時候,只顯示可視區域內的圖片,其它的圖片只有出現在可視區域內的時候才會被請求加載。
我們現在用原生的js實現簡單的圖片懶加載,主要利用的原理就是先不給設置src,而是把圖片的路徑放在data-src中,等待圖片被加載的時候將路徑取出放到src中。
HTML代碼
<div class="container"> <div class="img-area"> <img class="my-photo" </div> <div class="img-area"> <img class="my-photo" </div> <div class="img-area"> <img class="my-photo" </div> <div class="img-area"> <img class="my-photo" </div> <div class="img-area"> <img class="my-photo" </div></div>
判斷元素是否在可視區域
方法一:
1. 獲取屏幕可視區高度:document.documentElement.clientHeight
2. 獲取元素距頂部的高度:element.offsetTop
3. 獲取滾動高度:document.documentElement.scrollTop
4. 若滿足:2-3<1,那么元素就出現在可視區域
方法二:
1. 獲取元素到可視區域頂部的距離:var bound = element.getBoundingClientRect()
2. 獲取可視區域的高度:window.innerHeight
3. 若滿足bound.top<=window.innerHeight
,那么元素就出現在可視區域
方法三:
利用IntersectionObserver
函數自動觀察元素是否在可視區域內
var watch = new IntersectionObserver(callback,option);//開始觀察watch.observe(el);//停止觀察watch.unobserve(el);//關閉觀察器watch.disconnect();
js代碼
第一種很多人都用過,所以我們就用第二種寫一下
//判斷圖片是否出現在可視區域內function isInSight(el) { const bound = el.getBoundingClientRect(); const clientHeight = window.innerHeight; return bound.top <= clientHeight + 100;}//加載圖片let index = 0;function checkImgs() { const imgs = document.querySelectorAll('.my-photo'); for( let i = index; i < imgs.length; i++){ if(isInSight(imgs[i])){ loadImg(imgs[i]); index = i; } }}function loadImg(el) { if(!el.src){ const source = el.dataset.src; el.src = source; }}//函數節流//函數節流是很重要的思想,可以防止過于頻繁的操作domfunction throttle(fn,mustRun = 500) { const timer = null; let previous = null; return function () { const now = new Date(); const context = this; const args = arguments; if(!previous){ previous = now; } const remaining = now -previous; if(mustRun && remaining >= mustRun){ fn.apply(context,args); previous = now; } } }//調用函數window.onload=checkImgs;window.onscroll = throttle(checkImgs);
我們在用第三種方法寫一個demo
function checkImgs() { const imgs = Array.from(document.querySelectorAll(".my-photo")); imgs.forEach(item => io.observe(item));}function loadImg(el) { if (!el.src) { const source = el.dataset.src; el.src = source; }}const io = new IntersectionObserver(ioes => { ioes.forEach(ioe => { const el = ioe.target; const intersectionRatio = ioe.intersectionRatio; if (intersectionRatio > 0 && intersectionRatio <= 1) { loadImg(el); } el.onload = el.onerror = () => io.unobserve(el); });});
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答