LoginSignup
0
1

More than 1 year has passed since last update.

IntersectionObserver APIを使った遅延読み込み 実装方法の概要メモ

Last updated at Posted at 2021-05-07

IntersectionObserverAPIを使用するメリット

監視したい対象要素がIntersection(交差点)に達した時だけイベントを走らせてくれるのでパフォーマンスが良い。
(画面スクロール位置を読み込み続けるようなことが避けられる)

IntersectionObserverAPIの概要

画面の上部が指定した地点に達するたびにコールバック関数を呼び出す。

実装方法の概要

例として、header要素が画面から見えなくなったらスティッキーナビゲーションを表示する方法を記載します。

①監視したい要素を取

const header = document.querySelector('.header');

②オブジェクトを記載
条件を記述します。

const options = {
  root: null,   //viewport全体を監視対象にする場合null
  threshold: 0,   //0~1で指定。左の例だと、監視対象の要素の0%が画面から見えたら(監視対象の要素が見えなくなったら)③で記載するAPIが走るイメージ
}

③コールバック関数を記載
実行したいことを記載します。
引数にはAPIから返ってきたオブジェクトが配列で入る。
console.log(entry[0])でみてみると、スクロールのタイミングごとにisIntersecting=trueだったりfalseだったりする。
isIntersecting=trueだと、監視対象の要素がoptionで指定したthresholdに当てはまっているような意味。それを利用して実装する。

const callbackfunc = function(entry, observer) {
  // isIntersecting=falseだったら(監視対象要素が見えなくなったらステッキーナビをつける)
  if(!entry[0].isIntersecting) document.querySelector('nav').classList.add('sticky'); 
  // isIntersecting=trueだったら(監視対象要素が見えてたらステッキーナビを外す)
  if(!entry[0].isIntersecting) document.querySelector('nav').classList.remove('sticky'); 

  observer.unobserve(entry[0].target);  //一度実行したらそれ以降ターゲットが交差してもイベントを走らせないようにする
}

④IntersectionObserverAPIのコンストラクターを実行し、インスタンス化

let observer = new IntersectionObserver(callbackfunc, options);

第一引数に③で記載したコールバック関数、第二引数に②で記載したオブジェクトを渡します。

⑤IntersectionObserverAPIのobserveメソッドに監視したい要素を渡す

observer.observe(section);
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1