前兩章介紹了實現實現懶加載的兩種方式,下面介紹最後一種方式:經過
IntersectionObserver
這個新的API
實現。不過該API
有兼容性問題,Chrome 51+
支持。具體請移步MDN
查看。html
IntersectionObserver
介紹
IntersectionObserver
能夠異步觀察目標元素與其祖先元素或頂級文檔視窗(viewport
)交叉狀態的方法。也就是說它能夠幫助咱們去判斷一個元素是否出如今視口上。這裏只介紹用到的兩個屬性:git
IntersectionObserver.observe()
:使IntersectionObserver
開始監聽一個目標元素;isIntersecting
屬性:能夠判斷該元素是否出如今視口內;
根據上面介紹的那兩個屬性,咱們能夠遍歷每一個
img
元素,而後監聽每個元素,最後根據isIntersecting
屬性去判斷元素是否出如今視口內,從而決定是否讓它加載。github
HTML
結構和CSS
樣式<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
img {
height: 450px;
display: block;
margin-bottom: 20px;
}
</style>
</head>
<body>
<!--圖片地址暫時先保存在data-src這個自定義屬性上面-->
<img data-src="./img-loop/img/1.jpg" alt="懶加載1" />
<img data-src="./img-loop/img/2.png" alt="懶加載2" />
<img data-src="./img-loop/img/3.jpg" alt="懶加載3" />
<img data-src="./img-loop/img/4.jpg" alt="懶加載4" />
<img data-src="./img-loop/img/5.jpg" alt="懶加載5" />
</body>
</html>
複製代碼
JS
代碼document.addEventListener("DOMContentLoaded", () => {
if ("IntersectionObserver" in window) {
const imgs = document.getElementsByTagName("img");
const imageObserve = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
// 經過該屬性判斷元素是否出如今視口內
if (entry.isIntersecting) {
// entry.target可以取得那個dom元素
const img = entry.target;
img.src = img.dataset.src;
// 解除監視
imageObserve.unobserve(img);
}
});
});
[...imgs].forEach((img) => {
// 開啓監視每個元素
imageObserve.observe(img);
});
} else {
alert("您的瀏覽器不支持IntersectionObserver!");
}
});
複製代碼
至此一共介紹了三種實現懶加載的方式,我我的比較喜歡第三種實現方式,由於它會幫助咱們自動去監聽,加載完成以後能夠解除監聽,這樣咱們就不用本身去作節流優化。可是該方法須要考慮瀏覽器的兼容性。瀏覽器