KDE BLOG

Webデザインやコーディングについて書いています

【webpack速習】vol.9: Lazy Loading

下記ページをざっくりまとめます。

webpack.js.org

  • Lazy、つまり "オンデマンド"の読み込みは、サイトやアプリケーションを最適化するための優れた方法

Example

  • このコードでは、スクリプトが実行されるとすぐに、lodash.bundle.jsという別のチャンクが生成され、技術的には「Lazy load」される
  • 問題は、バンドルをロードするためにユーザーの操作が不要なことで、ページがロードされるたびにリクエストされることで、これは無駄なことでパフォーマンスに悪影響を与える。

ここでサンプルを試してみる。

  • ユーザーがボタンをクリックしたときにテキストをコンソールに出力するインタラクションを追加する
  • ただし、ボタンがクリックされるまでそのコード(print.js)をロードするのを待つ

ディレクトリ構成

project
  |- package.json
  |- webpack.config.js
  |- /dist
  |- /src
   |- index.js
+  |- print.js
  |- /node_modules

▼ src/print.js

console.log('The print.js module has loaded! See the network tab in dev tools...');

export default () => {
  console.log('Button Clicked: Here\'s "some text"!');
};

▼ src/index.js

import _ from 'lodash';

function component() {
  const element = document.createElement('div');
  const button = document.createElement('button');
  const br = document.createElement('br');

  button.innerHTML = 'Click me and look at the console!';
  element.innerHTML = _.join(['Hello', 'webpack'], ' ');
  element.appendChild(br);
  element.appendChild(button);

  // clickしたらLazyLoad
  button.onclick = e => import(/* webpackChunkName: "print" */ './print')
    .then(module => {
      const print = module.default;
      print();
    });

  return element;
}

document.body.appendChild(component());

これをビルドすると下記の結果となり、print.js の Lazy Load が成功しているのが分かる。

          Asset       Size  Chunks                    Chunk Names
print.bundle.js  417 bytes       0  [emitted]         print
index.bundle.js     548 kB       1  [emitted]  [big]  index
     index.html  189 bytes          [emitted]

Frameworks

多くのフレームワークやライブラリが、それぞれ Lazy Load、code splittingを行うために勧めるライブラリや方法などがある