<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Lazy Load via Intersection Observer</title>
<style>
/* Necessary so not all images are loaded at once */
img {
min-height: 500px;
}
</style>
</head>
<body>
<div class="box"><img data-src="https://picsum.photos/501/501" alt="Cute Cat"/></div>
<div class="box"><img data-src="https://picsum.photos/502/502" alt="Cute Cat"/></div>
<div class="box"><img data-src="https://picsum.photos/503/503" alt="Cute Cat"/></div>
<div class="box"><img data-src="https://picsum.photos/504/504" alt="Cute Cat"/></div>
<div class="box"><img data-src="https://picsum.photos/505/505" alt="Cute Cat"/></div>
<div class="box"><img data-src="https://picsum.photos/506/506" alt="Cute Cat"/></div>
<div class="box"><img data-src="https://picsum.photos/507/507" alt="Cute Cat"/></div>
</div>
<script>
const lazyLoadImages = (selector) => {
const images = document.querySelectorAll(selector),
loadImage = (img) => {
const src = img.getAttribute('data-src');
img.src = src;
},
obs = new IntersectionObserver((entries, self) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log('Entry is intersecting');
loadImage(entry.target);
self.unobserve(entry.target);
}
});
});
images.forEach(image => {
obs.observe(image)
});
};
lazyLoadImages('[data-src]');
</script>
</body>
</html>
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.