IntersectionObserver APIのオプション解説
Posted : 16 Apr 2020IntersectionObserver APIを用いて、ブラウザのスクロールに併せてHTMLを変更する処理を検証してみました。
公式情報:MDB web docs Intersection Observer API
環境
本稿を記載するにあたって動作確認を行ったブラウザは以下の通りである。
- Chrome 81.0.4044.113(Official Build)(64 ビット)
ベースとなるJavaScript
本稿では以下のJavaScriptを基に、IntersectionObserverの動作を紹介する。
targetクラスが付いた要素を監視し、rootと交差したらイベントを発火しtargetクラスの要素にshowクラスを追加する処理となっている。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
document.addEventListener('DOMContentLoaded', function() {
// IntersectionObserverのオプション設定
const options = {
root: null,
rootMargin: "0px",
threshold: 1.0
};
//IntersectionObserverのcallback関数の作成
const callback = (entries, observer) => {
entries.forEach( entry => {
if(entry.isIntersecting) {
// 要素が交差した際の動作
console.log('add show class');
entry.target.classList.add('show');
} else {
// 要素が交差から外れた際の動作
console.log('remove show class');
entry.target.classList.remove('show');
}
});
};
const observer = new IntersectionObserver(callback, options);
const el = document.querySelector('.target');
observer.observe(el);
});
rootの設定
rootオプションにelementを指定することで、ターゲットがどの要素と交差した際にイベントを発火できるか制御できる。
本稿ではnullを指定しているが、nullを指定した際はviewport(ブラウザの画面全体)が交差監視対象となる。
thresholdの設定
thresholdオプションを指定することで、「ターゲットとなる要素」が「root要素」とどの程度の割合交差したらイベントを発火させるか制御できる。
threshold 1.0
thresholdオプションを1.0と設定した場合の動作。
targetクラスの付いた要素が100%(つまり全て) root要素(今回の場合はviewport)内に交差した場合にイベントが発火する。
1
2
3
4
5
const options = {
root: null,
rootMargin: "0px",
threshold: 1.0
};
threshold 0.0
thresholdオプションを0.0と設定した場合の動作。 targetクラスの付いた要素が0%(つまり1pxでも) root要素(今回の場合はviewport)内に交差した場合にイベントが発火する。
1
2
3
4
5
const options = {
root: null,
rootMargin: "0px",
threshold: 0.0
};
threshold 0.5
thresholdオプションを0.5と設定した場合の動作。 targetクラスの付いた要素が50%(つまり半分) root要素(今回の場合はviewport)内に交差した場合にイベントが発火する。
1
2
3
4
5
const options = {
root: null,
rootMargin: "0px",
threshold: 0.5
};
rootMarginの設定
rootMarginオプションをを指定することで、「root要素に設けるmargin」と「ターゲット」が交差したらイベントを発火できる。
なお、以下のコードではthresholdを0.0に設定し、targetクラスの対が要素が0%(つまり1pxでも)交差した場合にイベントが発火する設定としている。
rootMarginに負の値を指定
rootMarginオプションに負の値をした場合は、「ターゲット」が「root要素からrootMarginを減らした範囲」に交差したらイベントを発火できる。
1
2
3
4
5
const options = {
root: null,
rootMargin: "-300px",
threshold: 0.0
};
動画では分かりやすいようにviewportの上部から300px、下部から300pxにborderを設定している。
rootMarginに正の値を指定
rootMarginオプションに正の値をした場合は、「ターゲット」が「root要素にrootMarginを足した範囲」に交差したらイベントを発火できる。
1
2
3
4
5
const options = {
root: null,
rootMargin: "300px",
threshold: 0.0
};
動画では多少分かりづらいが、ターゲットとroot要素(viewport)が交差する300px前、つまりスクロール操作によりターゲットが画面に表示される少し前に交差イベントを発火している。
おわりに
このページではYoutubeの動画を埋め込んでいます。
Youtubeの埋め込みではiframeを使用しますが、iframe部分でIntersectorObserverを用いた遅延読み込みを実装してページ読み込み時間の短縮を図っています。
- 遅延読込み無のLoad時間:1.774s
- 遅延読込み有のLoad時間:0.234s
※ N=10の平均値