Reputation: 87
I have an MVC project in which I am trying to implement lazy loading on images that don't appear at the top (or are in view) in the browser when say the homepage loads. Then as you scroll down the images would be loaded.
So far I have added this script to my master view to handle the lazy loading of the images:
<script>
document.addEventListener("DOMContentLoaded", function () {
var lazyloadImages;
if ("IntersectionObserver" in window) {
lazyloadImages = document.querySelectorAll(".lazy");
var imageObserver = new IntersectionObserver(function (entries, observer) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
var image = entry.target;
image.src = image.dataset.src;
image.classList.remove("lazy");
imageObserver.unobserve(image);
}
});
});
lazyloadImages.forEach(function (image) {
imageObserver.observe(image);
});
} else {
var lazyloadThrottleTimeout;
lazyloadImages = document.querySelectorAll(".lazy");
function lazyload() {
if (lazyloadThrottleTimeout) {
clearTimeout(lazyloadThrottleTimeout);
}
lazyloadThrottleTimeout = setTimeout(function () {
var scrollTop = window.pageYOffset;
lazyloadImages.forEach(function (img) {
if (img.offsetTop < (window.innerHeight + scrollTop)) {
img.src = img.dataset.src;
img.classList.remove('lazy');
}
});
if (lazyloadImages.length == 0) {
document.removeEventListener("scroll", lazyload);
window.removeEventListener("resize", lazyload);
window.removeEventListener("orientationChange", lazyload);
}
}, 20);
}
document.addEventListener("scroll", lazyload);
window.addEventListener("resize", lazyload);
window.addEventListener("orientationChange", lazyload);
}
})
</script>
The markup for the image this is the code:
<img data-src="~/Images/Icons/PinkArrow.png" class="lazy module-AEM2020-switching-img-pink-arrow-2" alt="">
Based on the class being lazy and src having been changed to data-src it should then load the image as you scroll down to that element.
However the image doesn't load and I am not sure what action to take next. Have I missed another reference or is my script not in the correct place?
This is taken from the browser debug.
Upvotes: 0
Views: 622