目录
上节: 代码分割(code spliting)下
上节目录如下:
其实在代码分割时已经用过懒加载了,src/index.js内容如下:
function getComponent() { const element = document.createElement('div'); return import(/* webpackChunkName: "lodash" */ 'lodash').then(({ default: _ }) => { const element = document.createElement('div'); element.innerHTML = _.join(['Hello', 'webpack'], ' '); return element; }).catch(error => 'An error occurred while loading the component');}// 按需加载,当点击了页面,才会引入lodash,也是单页应用路由懒加载的实现原理window.addEventListener('click', function(){ getComponent().then(component => { document.body.appendChild(component); })});
npm run build看生成的文件:
这三个文件将被用于浏览器,现在运行index.html打开f12:
如果不点击页面,就不会加载lodash文件,现在点击一下页面:
页面上出现hello webpack并且加载了lodash文件,这就是懒加载(按需加载 | 异步加载)
下节:css代码分隔(待更新)