本文實(shí)例講述了JavaScript實(shí)現(xiàn)圖片懶加載的方法。分享給大家供大家參考,具體如下:
懶加載是非常實(shí)用的提升網(wǎng)頁性能的方式,當(dāng)訪問一個頁面的時候,只顯示可視區(qū)域內(nèi)的圖片,其它的圖片只有出現(xiàn)在可視區(qū)域內(nèi)的時候才會被請求加載。
我們現(xiàn)在用原生的js實(shí)現(xiàn)簡單的圖片懶加載,主要利用的原理就是先不給設(shè)置src,而是把圖片的路徑放在data-src中,等待圖片被加載的時候?qū)⒙窂饺〕龇诺?span style="line-height: 25.2px; color: rgb(0, 0, 255);">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>
判斷元素是否在可視區(qū)域
方法一:
	1. 獲取屏幕可視區(qū)高度:document.documentElement.clientHeight
	2. 獲取元素距頂部的高度:element.offsetTop
	3. 獲取滾動高度:document.documentElement.scrollTop
	4. 若滿足:2-3<1,那么元素就出現(xiàn)在可視區(qū)域
方法二:
	1. 獲取元素到可視區(qū)域頂部的距離:var bound = element.getBoundingClientRect() 
	2. 獲取可視區(qū)域的高度:window.innerHeight 
	3. 若滿足bound.top<=window.innerHeight,那么元素就出現(xiàn)在可視區(qū)域
方法三:
	利用IntersectionObserver函數(shù)自動觀察元素是否在可視區(qū)域內(nèi)
var watch = new IntersectionObserver(callback,option);//開始觀察watch.observe(el);//停止觀察watch.unobserve(el);//關(guān)閉觀察器watch.disconnect();
js代碼
第一種很多人都用過,所以我們就用第二種寫一下
//判斷圖片是否出現(xiàn)在可視區(qū)域內(nèi)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;    }}//函數(shù)節(jié)流//函數(shù)節(jié)流是很重要的思想,可以防止過于頻繁的操作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;      }    }  }//調(diào)用函數(shù)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程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答