- Web applications are used more and more with mobile devices
- Many countries still have slow internet connections
- Load time has a huge impact on user experience
- Traditional apps load everything in the beginning
- Lazy loading means only loading parts after initial page load
Chunks are:
- polyfills.bundle.js: Polyfills required to run the app (see polyfills.ts)
- main.bundle.js: Actual application code along with vendor code (Angular)
- styles.bundle.css: Styles for the application
- inline.bundle.js: Tiny webpack loader to load the app
- By default, modules are loaded eagerly when the application starts
- Modules can loaded lazily by the router with
loadChildren
Main bundle is loaded when application starts
A feature module is loaded when it is routed to the first time
<a [routerLink]="['feature']">Click me</a>
- Angular CLI has built-in support for lazy loading
- Works for both development and production builds
- If
loadChildren
is detected chunks will be generated -> no extra configuration required
app.module.ts
const routes: Routes = [
{
path: '',
component: AppComponent
},
{
path: 'todos',
loadChildren: './todos/todos.module#TodosModule'
}];
@NgModule({
...
imports: [
...
RouterModule.forRoot(routes)
],
})
todos.module.ts
const routes: Routes = [
{
path: '',
component: TodosComponent
},
{
path: ':id',
component: EditTodoComponent
}
];
@NgModule({
...
imports: [
...
RouterModule.forChild(routes)
],
})
export class TodosModule {}
https://github.com/RoopeHakulinen/angular-lazy-loading
{
"scripts": {
...
"analyze": "ng build --prod --stats-json && webpack-bundle-analyzer dist/stats.json"
}
}
npm install webpack-bundle-analyzer --save-dev
npm run analyze