懒加载的实现

<!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是用来判断元素是否可见的

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 懒加载 为什么需要懒加载? 像vue这种单页面应用,如果没有应用懒加载,运用webpack打包后的文件将会异常的大...
    littlesiqi阅读 16,298评论 1 8
  • 懒加载 什么是懒加载 懒加载其实就是延迟加载,是一种对网页性能优化的方式,比如当访问一个页面的时候,优先显示可视区...
    grain先森阅读 2,640评论 0 79
  • 先将img标签的src链接设为同一张图片(比如空白图片),然后给img标签设置自定义属性(比如 data-src)...
    樊小勇阅读 642评论 3 5
  • Html5 语义化标签 headerfooternavarticlesection 文档类型定义 在h5中只需要写...
    路人丁0417阅读 1,116评论 0 2
  • 什么是懒加载 懒加载是一种 网页优化技术 作用 图片作为一种网页资源,请求时同样将占用网络资源,导致网页首屏的加载...
    蓝海00阅读 1,025评论 4 17