如何使用交叉观察器延迟加载 html div 标签



是否可以使用Intersection Observer API延迟加载整个div标签?

我使用交叉观察器 api 方法延迟加载图像。不知道如何为 html 元素执行此操作。

是的,您可以延迟将内容加载到divs 中。下面的示例只是使用 html() 在相交时使用随机字符串填充div。如果所需的内容是单独的 html 页面,则可以改用load()

function lazyDivs() {
  let lis = [].slice.call(document.querySelectorAll("div.lazy")),
    items = ["Aruba", "Jamaica", "Bermuda", "Bahama", "Key Largo", "Montego"];
  if (!lis.length) {
    //do nothing
  } else if ("IntersectionObserver" in window) {
    let o = new IntersectionObserver(function(es, obs) {
      es.forEach(function(e) {
        if (e.isIntersecting) {
          let li = $(e.target);
          li.html(items[Math.floor(Math.random() * items.length)]);
          //li.load('/path/to/html/fragment'); //option to load content from a separate page
          li.removeClass("lazy");
          o.unobserve(e.target);
        }
      });
    });
    lis.forEach(function(li) {
      o.observe(li);
    });
  } else {
    lis.forEach(function(li) {
      let l = $(li);
      l.html(items[Math.floor(Math.random() * items.length)]);
      //l.load('/path/to/html/fragment'); //option to load content from a separate page
      l.removeClass("lazy");
    });
  }
}
$(document).ready(function() {
  lazyDivs();
});
div {
  border: 1px solid blue;
  width: 100px;
  height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 10px auto;
}
<html>
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
  <div class="lazy"></div>
  <div class="lazy"></div>
  <div class="lazy"></div>
  <div class="lazy"></div>
  <div class="lazy"></div>
  <div class="lazy"></div>
  <div class="lazy"></div>
  <div class="lazy"></div>
  <div class="lazy"></div>
</body>
</html>

最新更新