교찰관찰자와 lazy loading

정은경·2021년 9월 6일
0

👸 Front-End Queen

목록 보기
206/265

리액트로 웹앱 만드는중
3가지 조건을 선택하면, 그 조건에 해당하는 이미지들이 화면에 나와야하는데
어떤 조건의 조합의 경우, 이미지가 없는 경우도 있고
이미지로딩 시간이 이미지마다 제각각이라서 화면이 좀...안예쁘다

Reference

키워드

Intersection Observer
Lazy-Loading
uselO

레이지 로딩 이미지 구현 feat. 리액트 훅스 "Intersection Observer"

  • 요구될때 이미지를 로딩하자! 미리 로딩 노노노노!

Intersection Observer

키워드들:

  • root
  • target
  • intersection ratio

Intersection Observer의 옵션들:

  • root : root는 target의 조상 중에서만 될 수 있음. 없거나 지정안하면 디폴트는 브라우저
  • rootMargin: root 주변의 마진. 디폴트는 0
  • threshold: 0과 1사이의 값 (0은 0%, 1은 100%). 디폴트 값은 0

Reference

로딩 속도 개선을 위한 여러 방법 중 하나

Lazy Loading

이미지/아이프레임/스크립트 등은 필요할 때까지는 읽지 않는
게으른 로딩(lazy loading) 기법을 사용하면 좋다

리액트로 앱개발을 할 때,
레이지 로딩을 위하여 별도의 라이브러리를 설치했었는데
와우!
브라우저에서 lazy 로딩을 아래와 같이 입력하면 지원한다니...!

<img src="image.jpg" loading="lazy">
<iframe src="https://example.com" loading="lazy">

Reference

아래의 링크가 해결해주었다!
고마웡!
https://heropy.blog/2019/10/27/intersection-observer/

Intersection Observer

  • 브라우저 뷰포트(Viewport)와 설정한 요소(Element)의 교차점을 관찰하며, 요소가 뷰포트에 포함되는지 포함되지 않는지 구별하는 기능을 제공
  • 비동기적으로 실행된다 => 고로! 렌더링 성능이나 이벤트 연속 호출 같은 문제가 없이 사용할 수 있다

DOMRectReadOnly 객체를 까보장

IntersectionObserver의 구조

IntersectionObserver의 options 요소들:

rootMargin

연습

// 관찰자 초기화
// const io = new IntersectionObserver(callback, options);
// options을 충족하면 callback 함수를 호출 함

// 관찰자의 파라미터 중 하나인 콜백 함수는
// 파라미터로 entries와 observer를 갖는다
// const callback = (entries, observer) => {}
/*
entries : IntersectionObserverEntry 인스턴스의 배열
 * boundingClientRect : 관찰 대상의 사격형 정보
 * intersectionRect : 관찰 대상의 교차한 영역 정보
 * intersectionRatio : intersectionRect / boundingClientRect의 값
 * isIntersecting
 * rootBounds : 루트 요소에 대한 사각형 정보를 반환 (rootMargin에 의해 변경. 디폴트는 null)
 * target : 관찰 대상 (element)
 * time : 문서가 작성된 시간을 기준으로 교차 상태 변경이 발생한 시간 (DOMHighResTimeStamp)
 */

// 관찰할 대상(element) 등록
// io.observe(element)

// const io = new IntersectionObserver((entries, observer) => {}, options);
// io.observe(element)

const callback = (entries, observer) => {
  entries.forEach((entry) => {
    if (!entry.isIntersecting) {
      return;
    }
    observer.unobserve(entry.target);
  });
};

const options = {
  root: document.getElementById("app"),
  rootMargin: "200px 0px",
  threshold: 0.3
};

const io = new IntersectionObserver(callback, options);

const div = document.querySelector("div");
io.observe(div);
io.unobserve(div);
io.disconnect();

헤로피님의 코드

https://codepen.io/heropark/pen/LYYjMQp

MDN의 intersection observer 코드

https://codesandbox.io/s/mdnintersection-oberserexamplethatworks-2ovqk?file=/index.html

Reference

profile
#의식의흐름 #순간순간 #생각의스냅샷

0개의 댓글