How to lazy load images in html with pure Javascript?

HARSH VATS - Nov 4 '20 - - Dev Community

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);
      });
Enter fullscreen mode Exit fullscreen mode

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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player