懒加载对页面的优化是非常重要的,当某些一开始不需要的资源我们不应该放在主文件中一起下载,而是等待使用的时候再去下载。懒加载能够减小主文件的大小,加快首屏的显示,缓解服务器的压力等优点。
webpack的懒加载是通过动态导入实现的。
来看一下具体的实现:
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"!');
};
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);
// 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 => {
const print = module.default;
print();
});
return element;
}
document.body.appendChild(component());
运行webpack,然后点击屏幕按钮,打开Network面板,可以看到最初加载的所有资源:
然后点击屏幕按钮,再看加载的资源,发现多了一个文件,这就是动态导入的模块会进行懒加载: