Web API : DOM.getBoundingClientRect()
getBoundingClientRect用于擷取某個元素相對于視窗的位置集合。集合中有top, right, bottom, left等屬性。
1.文法:這個方法沒有參數。
2.傳回值類型:
rectObject.top:元素上邊到視窗上邊的距離;
rectObject.right:元素右邊到視窗左邊的距離;
rectObject.bottom:元素下邊到視窗上邊的距離;
rectObject.left:元素左邊到視窗左邊的距離;

參考: https://www.jianshu.com/p/824eb6f9dda4
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>原生方式實作圖檔懶加載</title>
<style>
body {
text-align: center;
}
img {
width: 100%;
max-width: 300px;
height: 200px;
margin-bottom: 100px;
}
</style>
</head>
<body>
<div id="imgBoxFrame">
<div class="img-warpper">
<img class="lazyload" data-original="https://media3.giphy.com/media/k5GuJn7VslbpGQqHUB/200w.webp" src="https://media3.giphy.com/media/k5GuJn7VslbpGQqHUB/200w.webp">
</div>
<div class="img-warpper">
<img class="lazyload" data-original="https://media1.giphy.com/media/2A7yoKf2B87kotTApZ/200w.webp" src="https://media1.giphy.com/media/2A7yoKf2B87kotTApZ/200w.webp">
</div>
<div class="img-warpper">
<img class="lazyload" data-original="https://media2.giphy.com/media/3h1rwFW1PpLxD9xLUR/200w.webp">
</div>
<div class="img-warpper">
<img class="lazyload" data-original="https://media0.giphy.com/media/igHgY3xzYxmRcxwZBs/200w.webp">
</div>
<div class="img-warpper">
<img class="lazyload" data-original="https://media0.giphy.com/media/69v5dFsLtzdpaFZz2N/200w.webp">
</div>
</div>
<script>
// 原理
// 将資源路徑指派到img标簽的data-xx屬性中,而不是src屬性
// 擷取img節點距離浏覽器頂部的距離,如果小于或等于浏覽器視窗的可視高度,那麼就将data-xx的值指派到src裡去
// 用到的Web API
// DOM.getBoundingClientRect()
// 圖檔懶加載類
class LazyLoad {
constructor(el) {
this.imglist = Array.from(document.querySelectorAll(el)); // 需使用懶加載的圖檔集合
this.init(); // 初始化
}
// 判斷是否該圖檔是否可以加載
canILoad() {
let imglist = this.imglist,
len = imglist.length;
for (let i = len-1; i>=0; i--) {
// 縮寫,相當于if true
this.getBound(imglist[i]) && this.loadImage(imglist[i], i);
}
}
// 擷取圖檔與視窗的資訊
getBound(el) {
let bound = el.getBoundingClientRect();
let clientHeight = window.innerHeight;
// 圖檔距離頂部的距離 <= 浏覽器可視化的高度,進而推算出是否需要加載
return bound.top <= clientHeight - 100; // -100是為了看到效果,也可以去掉
}
// 加載圖檔
loadImage(el, index) {
// 擷取之前設定好的data-original值
let src = el.getAttribute('data-original');
// 指派到src,進而請求資源
el.src = src;
// 避免重複判斷,已經确定加載的圖檔應當從imglist移除
this.imglist.splice(index, 1);
}
// 當浏覽器滾動的時候,繼續判斷
bindEvent() {
window.addEventListener('scroll', () => {
this.imglist.length && this.canILoad();
});
}
// 初始化
init() {
this.canILoad();
this.bindEvent();
}
}
// 執行個體化對象,參數則是需要使用懶加載的圖檔類名
const lazy = new LazyLoad('.lazyload')
</script>
</body></html>