I am unable to get my images to lazy load with JavaScript. For some reason, the images just do not show up at all when I change the html from src to data-src. Then when I use an intersectionObserver to lazy load images, I can't get any images to show up on the page. Attached is my html, css and JS code;
html:
<div class="photo__container photo__container--one">
<img
data-src="portrait/1-vertical.jpeg"
alt=""
class="fade-in-img img-vertical-lazy"
/>
<img
data-src="portrait/2-vertical.jpeg"
alt=""
class="fade-in-img img-vertical-lazy"
/>
<img
data-src="portrait/3-vertical.jpeg"
alt=""
class="fade-in-img img-vertical-lazy"
/>
</div>
CSS:
.img-vertical-lazy {
height: 70rem;
width: auto;
}
JS:
const lazyImages = document.querySelectorAll('.img-vertical-lazy');
const appearLazy = {
threshold: 0.1
};
const lazyLoading = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (!entry.isIntersecting) return;
entry.target.src = entry.target.getAttribute('data-src');
lazyLoading.unobserve(entry.target);
});
}, appearLazy);
lazyImages.forEach(image => lazyLoading.observe(image));
loading=lazyon the images instead of all the JavaScript and the intersection observer :]loading=lazyonly has support on 74% of clients currently: caniuse.com/loading-lazy-attrsrcis correct? jsfiddle.net/8bxd5spn