Skip to content

Instantly share code, notes, and snippets.

@sxidsvit
Last active August 7, 2019 11:08
Show Gist options
  • Save sxidsvit/cde67d8433533d753281a13e7ba83143 to your computer and use it in GitHub Desktop.
Save sxidsvit/cde67d8433533d753281a13e7ba83143 to your computer and use it in GitHub Desktop.
Lazy load using API IntersectionObserver
// Source - https://habr.com/ru/company/ruvds/blog/453586/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Lazy Load Images</title>
</head>
<body>
<div>
<div style="">
<img class="lzy_img" src="lazy_img.jpg" data-src="img_1.jpg" />
<hr />
</div>
<div style="">
<img class="lzy_img" src="lazy_img.jpg" data-src="img_2.jpg" />
<hr />
</div>
<div style="">
<img class="lzy_img" src="lazy_img.jpg" data-src="img_3.jpg" />
<hr />
</div>
<div style="">
<img class="lzy_img" src="lazy_img.jpg" data-src="img_4.jpg" />
<hr />
</div>
<div style="">
<img class="lzy_img" src="lazy_img.jpg" data-src="img_5.jpg" />
<hr />
</div>
</div>
<script>
document.addEventListener("DOMContentLoaded", function () {
const imageObserver = new IntersectionObserver((entries, imgObserver) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const lazyImage = entry.target
console.log("lazy loading: ", lazyImage)
lazyImage.src = lazyImage.dataset.src
lazyImage.classList.remove("lzy_img");
imgObserver.unobserve(lazyImage);
}
})
});
const arr = document.querySelectorAll('img.lzy_img')
arr.forEach((v) => {
imageObserver.observe(v);
})
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment