【发布时间】: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