LoginSignup
5
5

More than 3 years have passed since last update.

IntersectionObserver 遅延読み込み

Last updated at Posted at 2020-09-23

IntersectionObserver

Intersection Observer APIは直訳すると交差監視APIという名前です。これは要素と要素の交差を検知するAPIになります。(参照: https://ics.media/entry/190902/)

従来の遅延読み込み

従来はscrollイベントや
lazyloadといったライブラリなどを使って遅延読み込みを行います。

なぜInterSectionObserverを使ったか

・SEO的に良さそうだから
 Googlebotが認識できる
・パフォーマンス的に良さそうだから
 scrollイベントのように絶えず要素の位置を確認することを避けられる
*参照: https://liginc.co.jp/498877

その他にも、個人的に
・ライブラリを読み込まず生のJavaScriptで実装できる
・JavaScriptを書くので実装している感が味わえるのではないか

と思い、今回使ってみました

実際に使ってみた

See the Pen qBZLyzX by なかもと ゆうと (@nakamoto_yuto) on CodePen.

感想

思ったより簡単にシンプルに実装できて楽でした:v_tone4:
生のJavaScriptで書いているので実装感があり楽しかったです。
Babel polyfillでIE対応そのままできてくれないかなーと願っていたのですがさすがにそこまでは無理でした:baby_tone5:
もし,いやbabel polyfillでいけるよ?という方いらっしゃいましたらぜひご教授していただけるととても嬉しいです。

IE対応

今回はintersection-observerというnpmを使用し,IE対応を行いました。
npmのドキュメントにはいくつか対応の方法が書かれていまして、実際に行なった方法を最初に紹介し、その後にその他の方法を紹介していきます。

今回の方法(npmをインストールし対応)

//terminalにて intersection-obseverをインストール
$npm install --save-dev intersection-observer

インストール後遅延読み込みを行うjsファイルにて

import 'intersection-observer'; // intersection-observerをimportし対応。

const lazyLoad = function () {
    // ターゲット指定
    const targets = Array.from(document.querySelectorAll("img[data-src]"));
    const img_path = "data-src";
    const options = {
      // 上下100px手前で発火
      rootMargin: "100px 0px"
    };
.....下記省略

もしくは


require('intersection-observer'); 

const lazyLoad = function () {
    // ターゲット指定
    const targets = Array.from(document.querySelectorAll("img[data-src]"));
    const img_path = "data-src";
    const options = {
      // 上下100px手前で発火
      rootMargin: "100px 0px"
    };

記述量かなり少なく済んだので楽でした!

HTML内でnpmを読み込み対応

<!-- Load the polyfill first.(IE対応するためのnpmを最初に読み込む) -->
<script src="path/to/intersection-observer.js"></script>

<!-- Load all other JavaScript. -->
<script src="app.js"></script> <!-- 遅延読み込みを行うjsファイル -->

モジュールバンドラーにて読み込みを行い対応(Webpack or Browserify)

// Require the polyfill before requiring any other modules.
require('intersection-observer');

require('./foo.js');
require('./bar.js');

おわりに

IntersectionObserver 他に比べて導入コストもほとんど変わらず楽にできるし,
jsを書いている感覚で楽しいのでぜひ一度も使ってみたことない方いらっしゃいましたら使ってみることをおすすめします!:muscle_tone2:

参照記事

ics.media JSでのスクロール連動エフェクトには
Intersection Observerが便利

画像を遅延読み込みしてみよう!Intersection Observer編
lazyload

5
5
2

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
5
5