How to lazy load images in html with pure Javascript?
HARSH VATS
Posted on November 4, 2020
Let's read this article at my place :)
If you just want to do image lazy loading without any understanding of the concepts involved because maybe this is your first time and you have to use in it your project then don't worry at all. I can assure you this article will give you everything already done so that you just need to copy paste.
1. Copy paste this code just before closing body tag
document.addEventListener('DOMContentLoaded', function () {
var lazyloadImages = document.querySelectorAll('img.lazy');
var lazyloadThrottleTimeout;
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);
});
2. Replace image src
attribute with data-src
If you have
<img src="<url>" />
then replace it with
<img data-src="<url>" />
3. This is the last point. Add class="lazy"
to all the images you want to lazy load.
Now you are good to go. Thank you for reading this article. I don't write articles for others, I write them for myself so I can use ready made code or revise my concepts. But if it helps you in any way then plz let me know here.
💖 💪 🙅 🚩
HARSH VATS
Posted on November 4, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.