• Q&A
  • 회원가입
  • 로그인

[js] JS - Lazyload (레이지로드)

Lazyload (레이지로드) : 스크롤할 때마다 콘텐츠가 나타나는 방식.

 

<style>

img {

  background: #F1F1FA;

  width: 400px;

  height: 300px;

  display: block;

  margin: 10px auto;

  border: 0;

}

</style>

 

<img src="https://ik.imagekit.io/demo/img/image1.jpeg?tr=w-400,h-300" />

<img src="https://ik.imagekit.io/demo/img/image2.jpeg?tr=w-400,h-300" />

<img src="https://ik.imagekit.io/demo/img/image3.jpg?tr=w-400,h-300" />

<img class="lazy" data-src="https://ik.imagekit.io/demo/img/image4.jpeg?tr=w-400,h-300" />

<img class="lazy" data-src="https://ik.imagekit.io/demo/img/image5.jpeg?tr=w-400,h-300" />

<img class="lazy" data-src="https://ik.imagekit.io/demo/img/image6.jpeg?tr=w-400,h-300" />

<img class="lazy" data-src="https://ik.imagekit.io/demo/img/image7.jpeg?tr=w-400,h-300" />

<img class="lazy" data-src="https://ik.imagekit.io/demo/img/image8.jpeg?tr=w-400,h-300" />

<img class="lazy" data-src="https://ik.imagekit.io/demo/img/image9.jpeg?tr=w-400,h-300" />

<img class="lazy" data-src="https://ik.imagekit.io/demo/img/image10.jpeg?tr=w-400,h-300" />


<script>

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

});

</script>

 

결과보기

 

방문 감사합니다. (즐겨찾기 등록: Ctrl + D)

찾아주셔서 감사합니다. Since 2012