madeas,
<!DOCTYPE html>
<html>
<head>
<title>Untitled</title>
<meta charset="utf-8">
<style type="text/css">
body{
display: flex;
flex-direction: column;
}
img{
width: 300px;
height: 350px;
background-color: #D3D3D3;
opacity: 0.2;
transition: .8s;
}
img.open{
opacity: 1;
}
</style>
</head>
<body>
<img class="lazy" src="" data-src="https://picsum.photos/300/350/?random&r=1" alt="">
<img class="lazy" src="" data-src="https://picsum.photos/300/350/?random&r=2" alt="">
<img class="lazy" src="" data-src="https://picsum.photos/300/350/?random&r=3" alt="">
<img class="lazy" src="" data-src="https://picsum.photos/300/350/?random&r=4" alt="">
<img class="lazy" src="" data-src="https://picsum.photos/300/350/?random&r=5" alt="">
<img class="lazy" src="" data-src="https://picsum.photos/300/350/?random&r=6" alt="">
<img class="lazy" src="" data-src="https://picsum.photos/300/350/?random&r=7" alt="">
<script>
function lazyLoad(elements) {
elements.forEach(image => {
if (image.intersectionRatio > 0) {
const img = image.target;
img.addEventListener('load', _ => {
img.classList.add("open");
}, false);
// set the src attribute to trigger a load
img.src = img.dataset.src;
// stop observing this element. Our work here is done!
observer.unobserve(img);
};
});
};
var observer = new IntersectionObserver(lazyLoad, {
// where in relation to the edge of the viewport, we are observing
rootMargin: "100px",
// how much of the element needs to have intersected
// in order to fire our loading function
threshold: 1.0
});
var lazyImages = document.querySelectorAll('img.lazy');
lazyImages.forEach(img => {
observer.observe(img);
});
</script>
</body>
</html>