懒加载的实现
2024-04-10 00:40:13  阅读数 926
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        p {
            height: 10vh;
        }
    </style>
</head>
<body>
    <p>LOREM IPSUM DOLOR SIT AMET...</p>
    <p>LOREM IPSUM DOLOR SIT AMET...</p>
    <p>LOREM IPSUM DOLOR SIT AMET...</p>
    <p>LOREM IPSUM DOLOR SIT AMET...</p>
    <p>LOREM IPSUM DOLOR SIT AMET...</p>
    <p>LOREM IPSUM DOLOR SIT AMET...</p>
    <p>LOREM IPSUM DOLOR SIT AMET...</p>
    <p>LOREM IPSUM DOLOR SIT AMET...</p>
    <p>LOREM IPSUM DOLOR SIT AMET...</p>

    <img data-src="home-banner.png" alt="">
    <img data-src="home-banner1.jpg" alt="">
    <img data-src="home-banner2.jpg" alt="">

    <p>LOREM IPSUM DOLOR SIT AMET...</p>
    <p>LOREM IPSUM DOLOR SIT AMET...</p>
    <p>LOREM IPSUM DOLOR SIT AMET...</p>
    <script>
        const images = document.querySelectorAll('img')
        const callback = entry => {
            entry.forEach(entry => {
                if (entry.isIntersecting) {
                    const image = entry.target;
                    const data_src = image.getAttribute("data-src");
                    image.setAttribute("src", data_src);
                    observer.unobserve(image);
                    console.log("触发");
                }
            })
        }
        const observer = new IntersectionObserver(callback);
        images.forEach(image => {
            observer.observe(image)
        })
    </script>
</body>
</html>

步骤1:


image.png

步骤2:


image.png

步骤3:


image.png
  1. getAttribute()方法介绍

elementNode.getAttribute(name):获取节点的属性,name是属性名称,比如ID,title,value等的值。

  1. setAttribute()方法介绍

elementNode.setAttribute(name,value):增加一个指定名称和值得新属性,或者把一个现有的属性设定为指定的值。name:要设置的属性名。value:要设置的属性值。

setAttribute()方法和getAttribute()方法经常一起使用达到操作目的。
如代码:
const data_src = image.getAttribute("data-src");
image.setAttribute("src", data_src);

  1. IntersectionObserver概念

IntersectionObserver接口(从属于Intersection Observer API)为开发者提供了一种可以异步监听目标元素与其祖先或视窗(viewport)交叉状态的手段。祖先元素与视窗(viewport)被称为根(root)。
intersectionRatio和isIntersecting是用来判断元素是否可见的