懒加载的实现

程序员 2024-9-12 00:29:57 28 0 来自 中国
<!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:

1.png 步调2:

步调3:


  • getAttribute()方法先容
elementNode.getAttribute(name):获取节点的属性,name是属性名称,好比ID,title,value等的值。

  • setAttribute()方法先容
elementNode.setAttribute(name,value):增长一个指定名称和值得新属性,大概把一个现有的属性设定为指定的值。name:要设置的属性名。value:要设置的属性值。
setAttribute()方法和getAttribute()方法经常一起利用到达操纵目的。
如代码:
const data_src = image.getAttribute("data-src");
image.setAttribute("src", data_src);

  • IntersectionObserver概念
IntersectionObserver接口(附属于Intersection Observer API)为开发者提供了一种可以异步监听目的元素与其先人或视窗(viewport)交织状态的本领。先人元素与视窗(viewport)被称为根(root)。
intersectionRatio和isIntersecting是用来判定元素是否可见的
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-18 18:18, Processed in 0.148897 second(s), 35 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表