avoid 429 error when load multiple images

Viewed 453

My webpage need to show about 40 images. For the amount to image to be downloaded from server, it cause 429 error randomly.

I want to guarantee my websites to show all the images for advertisement. how can I avoid 429 too many requests error? Is there any work around?

1 Answers

I use lazy loading to solve this problem. image won't be requested to server if user not scroll down to image tag itself.

  1. First I set data-srcto 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"/>
  1. 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

  1. you can use IntersectionObserver rather than eventListener, then you will need polyfill for IE user.
Related