首屏優化圖片懶加載

圖片懶加載有幾個重要的點:函數

1. 圖片 的src放到其餘屬性上,加統一的類名,供選擇和 加樣式,好比:

<img class="pic" alt="加載中"  
    data-src="http://ww1.sinaimg.cn/large/b0b365f5ly1fl8gmghdbsj20qo0bt3zo.jpg">

2. js懶加載函數

有幾個重點:性能

  1. 獲取可視區域的高度,ie9+ 用window.innerHeight
viewHeight = window.innerHeight || window.documentElement.clientHeight
  1. 獲取當前元素距離可視區域頂部的高度用 getBoundingClientRect().top

getBoundingClientRect 和 clientHeight的關係
spa

  1. getBoundingClientRect().top 小於 viewHeight的時候,給元素的src 賦值
ele.src = ele.getAttribute('data-src');
  1. 最後就是監聽滾動事件了

lazyload完整版

function lazyload() {
    const viewHeight = window.innerHeight || window.documentElement.clientHeight;
    let imgs = document.querySelectorAll('.pic');
    let num = 0, len = imgs.length;
    for(let i = num; i < len; i ++) {
        if(imgs[i].getBoundingClientRect().top < viewHeight) {
            console.log('i', i);
            imgs[i].src = imgs[i].getAttribute('data-src');
            num += 1 ;
        }
    }
}
window.addEventListener('scroll', lazyload);

固然這樣監聽滾動確定耗費性能,建議加上節流。可參考上一篇文章code

相關文章
相關標籤/搜索