JavaScript implements lazy loading of images

Attach the complete code directly

<!DOCTYPE html>
<html>
<head>
  <title>图片懒加载示例</title>
  <style>
    /* 设置占位符的大小和背景颜色 */
    .placeholder {
      width: 300px;
      height: 300px;
      background: gray;
    }
  </style>
</head>
<body>
  <h1>图片懒加载示例</h1>
  <div id="image-container">
    <!-- 占位符和懒加载图片的 data-src 属性 -->
    <div class="placeholder" data-src="image1.jpg"></div>
    <div class="placeholder" data-src="image2.jpg"></div>
    <div class="placeholder" data-src="image3.jpg"></div>
    ...
  </div>

  <script>
    // 创建 IntersectionObserver 实例
    const observer = new IntersectionObserver((entries, observer) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          // 当元素进入视口时,加载懒加载图片
          const img = entry.target;
          const src = img.getAttribute('data-src');
          img.src = src;
          observer.unobserve(img); // 停止对该元素的观察
        }
      });
    });

    // 获取所有拥有 data-src 属性的元素
    const placeholders = document.querySelectorAll('.placeholder');

    placeholders.forEach((placeholder) => {
      observer.observe(placeholder); // 开始观察每个占位符元素
    });
  </script>
</body>
</html>

This is to implement lazy loading of an image using native JavaScript. If you want to implement lazy loading of images in react projects, you can read this blog link of mine: One of the important means of optimizing react projects, lazy loading of images , which introduces the implementation of lazy loading of images in react projects and the introduction of IntersectionObserver

Guess you like

Origin blog.csdn.net/g2255yuuhgy/article/details/133342737