codingtcher.com
Theme Night
Home
Login

How to Lazy Load Offscreen Images javascript

Home » Tutorial Post » How to Lazy Load Offscreen Images javascript
<style>
     .imgMainDiv{
       width: 80%;
       margin: 0 auto 20px auto;
     }
     .imgDiv{
        max-width: 640px;
        height: 35vh;
        background: black;
        margin: 20px auto 0 auto;
     }
     .imgDiv img{
       width: 100%;
       height: 100%;
     }
</style>

<div class="imgMainDiv">
<div class="imgDiv"><img alt="image not loaded" src="/images/loading.svg" data-src="/images/demoimg/1.jpg"></div>
<div class="imgDiv"><img alt="image not loaded" src="/images/loading.svg" data-src="/images/demoimg/2.webp"></div>
<div class="imgDiv"><img alt="image not loaded" src="/images/loading.svg" data-src="/images/demoimg/3.webp"></div>
<div class="imgDiv"><img alt="image not loaded" src="/images/loading.svg" data-src="/images/demoimg/4.webp"></div>
<div class="imgDiv"><img alt="image not loaded" src="/images/loading.svg" data-src="/images/demoimg/5.jpg"></div>
<div class="imgDiv"><img alt="image not loaded" src="/images/loading.svg" data-src="/images/demoimg/6.jpg"></div>
<div class="imgDiv"><img alt="image not loaded" src="/images/loading.svg" data-src="/images/demoimg/7.jpg"></div>
<div class="imgDiv"><img alt="image not loaded" src="/images/loading.svg" data-src="/images/demoimg/8.jpg"></div>
<div class="imgDiv"><img alt="image not loaded" src="/images/loading.svg" data-src="/images/demoimg/9.jpg"></div>
<div class="imgDiv"><img alt="image not loaded" src="/images/loading.svg" data-src="/images/demoimg/10.jpg"></div>
</div>

<script>
function lazyLoadImages(){
  setTimeout(function(){
        var elements = document.querySelectorAll("*[data-src]");
        for (var i = 0; i < elements.length; i++){
                var boundingClientRect = elements[i].getBoundingClientRect();
                if (elements[i].hasAttribute("data-src") && boundingClientRect.top < window.innerHeight && boundingClientRect.left < window.innerWidth){
                    elements[i].setAttribute("src", elements[i].getAttribute("data-src"));
                    elements[i].removeAttribute("data-src");
                }
          }
        },500);
}
window.addEventListener('scroll', lazyLoadImages);
window.addEventListener('load', lazyLoadImages);
window.addEventListener('resize', lazyLoadImages);
</script>

Related Post