lazy

2022. 10. 21. 14:48Other/Programming

728x90
반응형

 

페이지를 불러오는 시점 에 당장 필요하지 않은 리소스는 추후에 로딩하게 하는 기술입니다.

 

 

사용자가 보지 않는 것들을 당장 로딩 하지 않고 필요할 때 로딩합니다.
 데이터를 필요한 시점에 가져오는 방식을 지연(Lazy) 방식이라고 한다.
대표적 예시

 1. <img> 태그

 scroll event를 그대로 들으면 성능상의 문제가 있기 때문에 throttle을 setTimeOut을 이용해서 구현합니다.
class에서 lazy를 걷어내고, img.dataset.src를 통해 data-src에 접근하여 `src prop에 다시 넣어줍니다.
ex)
<img src="https://ik.imagekit.io/demo/img/image1.jpeg?tr=w-400,h-300" />
...

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

2. css background 

lazy class가 제거되면 사진이 적용됩니다.
ex)

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


#bg-image.lazy {
   background-image: none;
   background-color: #F1F1FA;
}
#bg-image {
  background-image: url("https://ik.imagekit.io/demo/img/image10.jpeg?tr=w-600,h-400");
  max-width: 600px;
  height: 400px;
}

장점

1.  처음에 일부만 다운로드 되기 때문에 성능이 향상 된다.

2. 콘텐츠가 지속적으로 공급 되기 때문에 사용자가 이탈할 확률을 낮출 수 있다.

3. 사용자가 필요로 하는 경우에만 콘텐츠를 불러오기 때문에 비용이 감소 된다.

 

Lazy - Loading 구현을 확인하는 법
크롬 개발자 도구 -> 네트워크 -> img 를 들어가 스크롤 할 때, 어떤 이미지들이 다운로드 받아지는지 보면 됩니다.
728x90
반응형

'Other > Programming' 카테고리의 다른 글

match()  (0) 2022.10.27
reduce  (0) 2022.10.26
메모이제이션  (0) 2022.10.11
동적 계획법  (0) 2022.08.11
서버리스  (0) 2022.07.31