본문 바로가기
개발노트

메인페이지 이미지 로딩 시간 줄이기

by SoonNote 2022. 4. 29.
반응형

메인페이지에 이미지가 많거나 용량이 많은 것들이 있으면 로딩시간이 길어진다.

이때 lazy라는 것을 사용하여 로딩시간을 많이 단축 시킬 수 있다.

 

lazy는 이미지 로딩을 하지 않고 있다가 사용자가 해당위치에 왔을때 이미지를 로딩하는 것으로 페이지 로딩시간을 단축시켜준다.

 

<img id="imgView" class="lazy" data-src="/cmm/imageLoad.do?path=${test.test}&storeNm=${test.test}">

<script>

document.addEventListener("DOMContentLoaded", function() {
      var lazyloadImages;    

      if ("IntersectionObserver" in window) {
        lazyloadImages = document.querySelectorAll(".lazy");
        var imageObserver = new IntersectionObserver(function(entries, observer) {
          entries.forEach(function(entry) {
            if (entry.isIntersecting) {
              var image = entry.target;
              image.src = image.dataset.src;
              image.classList.remove("lazy");
              imageObserver.unobserve(image);
            }
          });
        });

        lazyloadImages.forEach(function(image) {
          imageObserver.observe(image);
        });
      } else {  
        var lazyloadThrottleTimeout;
        lazyloadImages = document.querySelectorAll(".lazy");

        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>

 

이미지 슬라이드에서 이미지가 안나오는 경우도 종종 생김으로 무조건 거는게 좋은건 아닌 것 같다.

반응형