I use lazy loading
to solve this problem.
image won't be requested to server if user not scroll down to image tag itself.
- First I set
data-src
to which I want to apply lazy loading.
<img data-src="../img2.png" class="lazy"/>
<img data-src="../img2.png" class="lazy"/>
<img data-src="../img2.png" class="lazy"/>
- inject script after body tags.
here I wrote js script
document.addEventListener("DOMContentLoaded", function () {
const lazyLoadImages = document.querySelectorAll(".lazy");
let lazyLoadThrottleTimeout;
function lazyLoading() {
if (lazyLoadThrottleTimeout) {
clearTimeout(lazyLoadThrottleTimeout);
}
lazyLoadThrottleTimeout = setTimeout(function () {
const scrollTop = window.pageYOffset;
lazyLoadImages.forEach(function (image) {
if (image.offsetTop < window.innerHeight + scrollTop) {
image.src = image.dataset.src;
image.classList.remove("w_lazy");
}
});
if (lazyLoadImages.length) {
document.removeEventListener("scroll", lazyLoading);
window.removeEventListener("resize", lazyLoading);
window.removeEventListener("orientationchange", lazyLoading);
}
}, 35);
}
document.addEventListener("scroll", lazyLoading);
window.addEventListener("resize", lazyLoading);
window.addEventListener("orientationchange", lazyLoading);
});
the main idea is eventListener "scroll" and "resize" wait until user scrolling down to image tag, put src
image path using data-src
- you can use
IntersectionObserver
rather than eventListener, then you will need polyfill for IE user.