How to lazy load images in html with pure Javascript?

Harsh Vats on October 20, 2020

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.

First method

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) {

          lazyloadThrottleTimeout = setTimeout(function () {
            var scrollTop = window.pageYOffset;
            lazyloadImages.forEach(function (img) {
              if (img.offsetTop < window.innerHeight + scrollTop) {
                img.src = img.dataset.src;
            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>" />

This will prevent the images to start loading instantaneously as there is not src attribute on the image.

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 via email.

Second method

Add loading="lazy" to any image you want and it will be rendered lazily.

But here's the thing

This method is not supported by safari yet, but is supported by Chrome and firefox.

First VS Second method

  1. First method will not work if javascript is disabled.
  2. Second method is not supported by all browsers yet.
  3. First method will not render images at all if javascript didn't run for any reason.
  4. On the other hand, second method is just progressive enhancement. What it means is that the browsers which do not support loading attribute will simple ignore this and render images normally.