【问题标题】:Include text with images being lazy loaded using Intersectionobserver包含使用 Intersectionobserver 延迟加载图像的文本
【发布时间】:2023-02-15 00:42:52
【问题描述】:

我对 Intersection Observer 不熟悉,所以我怎么能像 H2 标签一样只在图像出现时加载? 这是我的代码

const images = document.querySelectorAll('img[data-src]');

const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      const image = entry.target;
      image.src = image.dataset.src;
      observer.unobserve(image);
    }
  });
});

images.forEach((image) => {
  observer.observe(image);
});

这是 html

<div>
<img src = "1.jpg">
<!-- <H2>title 1</h2>-->

<img data-src = "2.jpg">
<!-- <H2>title 2</h2>  lazy loaded here-->

<img data-src = "3.jpg">
<!-- <H2>title 3</h2>  lazy loaded here-->
</div>

【问题讨论】:

  • 延迟加载内容有什么意义吗?除非你的 html 文件很大,否则可能没有 - 否则你需要向图像添加某种数据属性,告诉它从哪里获取内容(可能需要 ajax 加载它,否则你只是移动你的 html从你的页面到你的js文件)

标签: javascript html intersection-observer


【解决方案1】:

不确定你是否真的需要 intersectionObserver,除非你的网站真的很拥抱,有很多图片,有一个简单的解决方案。

只需检查图像是否已加载,是否放置了 h2 显示块。 img 有 src 而不是 data-src,开头的 h2 是 display none。

检查是用一个 addeventlistener 完成的,它在加载以清理东西时被删除。

如果你有一个巨大的站点,你可以在 intersectionobserver 中使用它。

Array.from(document.querySelectorAll('img')).forEach(elim => {
  elim.addEventListener('load', checkIm);
});

function checkIm(evt) {
  const image = evt.target;
  console.log(image);
  const h = image.nextElementSibling;
  console.log(h);
  h.style.display = 'block';
  image.removeEventListener('load', checkIm);
}
img {
  display: block;
}

h2 {
  display: none;
}
<div>
  <img src="https://picsum.photos/id/237/600/600">
  <h2>title 1</h2>

  <img src="https://picsum.photos/id/182/600/600">
  <h2>title 2</h2>

  <img src="https://picsum.photos/id/121/600/600">
  <h2>title 3</h2>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多