Skip to content

Latest commit

 

History

History
127 lines (102 loc) · 2.5 KB

File metadata and controls

127 lines (102 loc) · 2.5 KB

Lazy Loading


Background

  • 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

Lazy Loading

  • Traditional apps load everything in the beginning
  • Lazy loading means only loading parts after initial page load

Default Bundling

Build without lazy loading

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

Custom Chunks

Build with lazy loading


Angular Module Loading

  • By default, modules are loaded eagerly when the application starts
  • Modules can loaded lazily by the router with loadChildren

Angular Module Loading

Main bundle is loaded when application starts

Main Module

Angular Module Loading

A feature module is loaded when it is routed to the first time

<a [routerLink]="['feature']">Click me</a>

Lazy Loaded Module


Angular CLI

  • 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

Router Configuration

app.module.ts

const routes: Routes = [
  {
    path: '',
    component: AppComponent
  },
  {
    path: 'todos',
    loadChildren: './todos/todos.module#TodosModule'
  }];

@NgModule({
  ...
  imports: [
    ...
    RouterModule.forRoot(routes)    
  ],
})

Router Configuration

todos.module.ts

const routes: Routes = [
  {
    path: '',
    component: TodosComponent
  },
  {
    path: ':id',
    component: EditTodoComponent
  }
];

@NgModule({
  ...
  imports: [
    ...
    RouterModule.forChild(routes)
  ],
})
export class TodosModule {}

Demo

https://github.com/RoopeHakulinen/angular-lazy-loading


Analyzing Bundle Sizes

{
  "scripts": {
     ...
    "analyze": "ng build --prod --stats-json && webpack-bundle-analyzer dist/stats.json"
  }
}
npm install webpack-bundle-analyzer --save-dev
npm run analyze