9.懒加载

懒加载

  • 用户的交互时需要功能才加载

  • 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() {
  var element = document.createElement('div');
  var button = document.createElement('button');
  var br = document.createElement('br');

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

  // Note that because a network request is involved, some indication
  // of loading would need to be shown in a production-level site/app.
  button.onclick = e => import(/* webpackChunkName: "print" */ './print').then(module => {
    var print = module.default;

    print();
  });

  return element;
}

document.body.appendChild(component());
  • 结果: 打印功能分离,在点击时加载
Version: webpack 4.41.6
Time: 4160ms
Built at: 2020-02-18 15:00:53
          Asset       Size  Chunks                    Chunk Names
  app.bundle.js   1.02 MiB       0  [emitted]  [big]  app
     index.html  186 bytes          [emitted]
print.bundle.js  890 bytes       1  [emitted]         print
Entrypoint app [big] = app.bundle.js
[./node_modules/_webpack@4.41.6@webpack/buildin/global.js] (webpack)/buildin/global.js 472 bytes {0} [built]
[./node_modules/_webpack@4.41.6@webpack/buildin/module.js] (webpack)/buildin/module.js 497 bytes {0} [built]
[./src/index.js] 705 bytes {0} [built]
[./src/print.js] 214 bytes {1} [built]
    + 1 hidden module

框架

  • 许多框架和类库对于如何用它们自己的方式来实现(懒加载)都有自己的建议。这里有一些例子:
    • React: Code Splitting and Lazy Loading
    • Vue: Lazy Load in Vue using Webpack's code splitting
    • AngularJS: AngularJS + Webpack = lazyLoad by @var_bincom
posted @ 2020-03-22 11:09  KevinTseng  阅读(77)  评论(0编辑  收藏  举报