懒加载的实现

简介: 懒加载的实现
<!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

  • 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是用来判断元素是否可见的
目录
相关文章
|
11天前
|
弹性计算 关系型数据库 微服务
基于 Docker 与 Kubernetes(K3s)的微服务:阿里云生产环境扩容实践
在微服务架构中,如何实现“稳定扩容”与“成本可控”是企业面临的核心挑战。本文结合 Python FastAPI 微服务实战,详解如何基于阿里云基础设施,利用 Docker 封装服务、K3s 实现容器编排,构建生产级微服务架构。内容涵盖容器构建、集群部署、自动扩缩容、可观测性等关键环节,适配阿里云资源特性与服务生态,助力企业打造低成本、高可靠、易扩展的微服务解决方案。
1234 5
|
10天前
|
机器学习/深度学习 人工智能 前端开发
通义DeepResearch全面开源!同步分享可落地的高阶Agent构建方法论
通义研究团队开源发布通义 DeepResearch —— 首个在性能上可与 OpenAI DeepResearch 相媲美、并在多项权威基准测试中取得领先表现的全开源 Web Agent。
1217 87
|
11天前
|
云栖大会
阿里云云栖大会2025年9月24日开启,免费申请大会门票,速度领取~
2025云栖大会将于9月24-26日举行,官网免费预约畅享票,审核后短信通知,持证件入场
1797 13
|
20天前
|
人工智能 运维 安全
|
3天前
|
资源调度
除了nrm-pm,还有哪些工具可以管理多个包管理器的源?
除了nrm-pm,还有哪些工具可以管理多个包管理器的源?
235 127