Intersection Observer

๋™์˜์ƒ ๋ ˆ์ด์–ด ํ”Œ๋ ˆ์ด์–ด ์ž‘์—…์„ ์ง„ํ–‰ํ•˜๋ฉด์„œ, ํ˜„์žฌ ํŠน์ • element๊ฐ€ ๋ณด์ด๋Š”์ง€ ์—ฌ๋ถ€์— ๋”ฐ๋ผ์„œ ๋ ˆ์ด์–ด ํ”Œ๋ ˆ์ด์–ด ํ˜น์€ ์ƒ๋‹จ ๋น„๋””์˜ค ํ”Œ๋ ˆ์ด์–ด๋ฅผ ๋…ธ์ถœ ์ด๋ฒคํŠธ๋ฅผ ์ฒ˜๋ฆฌํ•ด์•ผํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์ƒ๊ฒผ๋‹ค.

cjmall Screenshot

Intersection Observer API๋Š” element๊ฐ€ viewport์—์„œ "๋ณด์ด๋Š”์ง€ ์•ˆ๋ณด์ด๋Š”์ง€"(visible)์— ๋”ฐ๋ผ ๋น„๋™๊ธฐ๋กœ ์ด๋ฒคํŠธ ์ฒ˜๋ฆฌ๋ฅผ ํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ค€๋‹ค.

const intersectionObserver = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            // do something
            observer.unobserve(entry.target);
        }
    });
});

intersectionObserver.observe(element);

๊ธฐ๋ณธ์ ์ธ ์‚ฌ์šฉ๋ฐฉ๋ฒ•์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

๊ทธ๋ฆฌ๊ณ  ์•„๋ž˜์˜ 3๊ฐ€์ง€ ์˜ต์…˜์„ ์ค„ ์ˆ˜ ์žˆ๋‹ค.

  • root : Element ๋˜๋Š” null ๊ฐ’์œผ๋กœ target (๊ด€์ธก ๋Œ€์ƒ) ์„ ๊ฐ์‹ธ๋Š” element ๋ฅผ ์ง€์ •ํ•œ๋‹ค๊ณ  ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

    ๋งŒ์•ฝ null ๋กœ ์ง€์ •ํ•œ๋‹ค๋ฉด viewport๋กœ ์ง€์ •๋ฉ๋‹ˆ๋‹ค.

  • rootMargin : root์š”์†Œ๋ฅผ ๊ฐ์‹ธ๋Š” margin ๊ฐ’์„ ์ง€์ •ํ•œ๋‹ค.

  • threshold : target element ๊ฐ€ root ์™€ ๋ช‡ % ๊ต์ฐจํ–ˆ์„ ๋•Œ, callback ์„ ์‹คํ–‰ํ• ์ง€ ๊ฒฐ์ •ํ•˜๋Š” ๊ฐ’์ด๋‹ค.

์ด๋ฒˆ์˜ ๊ฒฝ์šฐ์—๋Š” ํ—ค๋”์˜ ๋†’์ด์™€ ํ˜„์žฌ ํ”Œ๋ ˆ์ด์–ด๊ฐ€ ๋…ธ์ถœ๋˜๋Š” ๋น„์œจ์„ ๊ณ„์‚ฐํ•˜์—ฌ ๋ ˆ์ด์–ด ํ”Œ๋ ˆ์ด์–ด๋ฅผ ๋…ธ์ถœํ•ด์•ผํ•˜๋Š” ๊ฒฝ์šฐ์—ฌ์„œ threshold ์˜ต์…˜์„ ์‚ฌ์šฉํ•ด ์˜์—ญ ๋…ธ์ถœ์—ฌ๋ถ€๋ฅผ ํŒ๋‹จํ–ˆ๋‹ค.

_setObserveIstance: function(videoPlayerView, controlOptions){
          var s = this;
          var $header = $('#header');
          var $player = $('#player');
          var threshold = ($header.outerHeight() / $player.height()).toPrecision(1);
          var observerOptions = {
                  threshold: Number(threshold)
          };
            // ์žฌ์ƒ์ค‘์ธ ๊ฒฝ์šฐ ๋ ˆ์ด์–ด ํ”Œ๋ ˆ์ด์–ด ๋…ธ์ถœ
          var observerInstance = new IntersectionObserver(function(entries, observer) {
                entries.forEach(function(entry){
                    if(entry.intersectionRatio > threshold){
            // ๋ณด์—ฌ์ง€๋Š” ์˜์—ญ ๋น„์œจ์ด threshold๋ณด๋‹ค ํฌ๋ฉด ์ƒ๋‹จ ํ”Œ๋ ˆ์ด์–ด ๋…ธ์ถœ
                    }else{
            // ๋ณด์—ฌ์ง€๋Š” ์˜์—ญ ๋น„์œจ์ด threshold๋ณด๋‹ค ์ž‘์œผ๋ฉด ๋ ˆ์ด์–ดํ”Œ๋ ˆ์ด์–ด ๋…ธ์ถœ
                    }
                });
            }, observerOptions);

            observerInstance.observe(videoPlayerView.$el.get(0));
      }
    } );

๋™์˜์ƒ์ด ์ผ์‹œ์ •์ง€๋˜๊ฑฐ๋‚˜ ์ข…๋ฃŒ๋œ ๊ฒฝ์šฐ์—๋Š” observer.unobserve(element); ๋กœ observing์„ ์ข…๋ฃŒํ•ด์ฃผ์—ˆ๋‹ค.

์ฐธ์กฐ ํŽ˜์ด์ง€

Last updated

Was this helpful?