Our Tech Journal
  • Introduction
  • Overview
    • Introduction
  • Javascript
    • JS Runtime, Env Context, Scopes, Hoisting & Execution Cycle, var/let/const, this
    • Javascript Runtime Env
      • Event loops
    • What are WebVitals
    • Module Patterns in JS - CommonJS, AMD and ES6 classes
    • Lexical Environment in JS
    • var vs let/const
    • Temporal Dead Zone (TDZ)
    • Execution Context
    • 'this' keyword
    • undefined value in JS
    • Function expressions vs Function statements
    • Javascript Code Execution
    • Closures
    • JS : Object Oriented Programming
    • Prototypal Inheritance
      • Creating Object in Javascript
    • NaN
    • Objects
      • Ways to create
      • ways to check if Object is empty
      • Object's own properties
    • use strict mode
    • typeof vs instanceof
    • Promise
    • localStorage and SessionStorage
    • Event handlers
    • Event bubbling
    • Event Delegation
    • XHR Request
    • Promise Error: Catch vs Error Function in Then
    • Immutability
    • Useful Code samples
    • window, document, screen
    • window.innerheight, outer height, screen.height
    • JS Design Patters
    • Interview Questions
    • Encapsulation - Module Patterns in JS
    • Redesigning services using Entity framework approach
  • JS Functions
    • JS Array - Slice vs Splice
  • PWA
    • What is PWA
  • ES6
    • Sets
    • Maps
    • spread vs destructure operator
  • Web
    • http / https
    • CORS
    • CSRF
    • XSS Attack
    • What is SPA
    • Semantic Elements in HTML
  • Angular 4
    • Angular vs React
    • Change Detection
    • Lazy Loading of modules
    • Preloading
    • AOT Compilation
    • Route Guards
    • Shared Modules
    • Tree Shaking
    • LifeCycle Hooks
    • ngRx
    • Observables
    • Observable vs Subject
      • BehaviorSubject
    • Observables vs Promises
    • Builtin Directives
      • Temp
      • Structural Directives
        • ngForTemp
        • ngSwitch
        • ngFor
        • ngIf
      • Attribute Directives
        • temp
        • ngClass
        • ngStyle
    • Routing
      • Routing in Angular
      • Setting up basic routing
      • routerLink and routerLinkActive
      • router.navigate and ActivatedRoute
      • Route Params as Observables
      • redirectTo
      • relativeTo
      • pathMatch
      • ActivatedRoute
      • Routing in Angular
      • Passing Data with Route
      • Route Parameters
    • Intercept HTTP request
    • Custom Directives
    • Communication between components
    • Angular Modules
    • Reactive Forms
    • Unit Testing
      • TestBed and component fixture
      • Testing HttpClient requests
      • Testing fakeAsync
  • GraphQL
    • Introduction
    • Server
    • Client Side
    • GraphQL in Angular
    • Queries
      • temp
      • query with parameters
      • aliases
      • fragments
      • @include directive
      • @skip directive
      • variables
      • Inline Fragments
  • CSS
    • What is Box model?
    • display: block, inline or inline-block
    • CSS Selector: Combinators
    • CSS Pseudo-classes
    • CSS Pseudo-elements
    • CSS3 Filter
    • CSS3 Transitions
    • Media Queries
    • Flex vs Grid
    • CSS 3 Grids
    • What is Flexbox?
    • position: relative vs absolute
  • SASS
    • Mixins
    • Lists
    • Maps
  • RxJS
    • throttle vs debounceTime
    • distinctUnitChange
    • reduce vs scan
  • Typescript
    • Typeguards
    • Pattern Matching with Typescript
    • TS Decorators
    • Using LINQ in TS
  • NodeJS
    • NodeJS Security Checklist
    • What is Node.js
  • REACT
    • React - VDOM - Under the hood
    • Synthetic events in React
    • Routing - React Router 4
    • React Custom hook
    • Higher-Order Component
    • REDUX
    • Redux Thunk vs Redux Saga
    • forceUpdate()
    • Storing Data in React
    • Error Handling
    • React Context
    • How React-Native works
    • refs
    • Server-side Rendering
    • Jest setup file
    • React-test-renderer
    • Lifecycle
    • React Testing Library
    • React Query
  • JWT
    • What is JWT and How it works
Powered by GitBook
On this page
  • 1. First setup the routing for the photos module:
  • 2. Next, use this router in the photos module:
  • 3. Use loadChildren in the root module's route configuration
  1. Angular 4

Lazy Loading of modules

In Angular 2 / 4, you can divide the various functionalities / features of your application into modules. Taking the example of our Photo Albums application, Home page/view , where we show the albums of the user, could be the default/root module. The 'Photos' view, that shows photos inside an album doesn't need to be loaded from the starting of the app, it could be loaded lazily later when user selects an album. We can wrap all the components needed for Photos view in a child module of the app's root module . Similarly, the 'User Settings' component could be wrapped in a separate child module. And then we can configure our Router to load Photos and User Settings modules lazily.

This helps to bring down the initial size of the application bundle thereby improving performance of the application.

Lets say, we have 2 components used in an album's Photos view: 1. PhotosGrid - a grid view of photos in an album 2. PhotoDetails - shows an individual photo along with its details like date and caption for each photo.

In order to have these components loaded lazily, we have to include these components inside a separate module, lets call it 'photos' module created under photos folder:

1. First setup the routing for the photos module:

./app/modules/photos/photos.routes.ts

import { Routes } from '@angular/router';

import { PhotosGrid } from './photos/grid.component';
import { PhotoDetails } from './photos/details.component';


export const routes: Routes = [
    { path: '', component: PhotosGrid },
    { path: '/:id', component: PhotoDetails }
];

2. Next, use this router in the photos module:

./app/modules/photos/photos.module.ts

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

import { PhotosGrid } from './photos/grid.component';
import { PhotoDetails } from './photos/details.component';
import { routes } from './photos.routes';


@NgModule({
  imports: [
    RouterModule.forChild(routes)
  ],
  declarations: [PhotosGrid, PhotoDetails]
})
export class PhotosModule { }

Note the use of RouterModule's forChild method above.

3. Use loadChildren in the root module's route configuration

Finally, use loadChildren in the root module's route configuration

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
...
import { Route, RouterModule } from '@angular/router';

import { AppComponent } from './app.component';
import { LoginComponent } from '../../components/login/app-login.component';
import { AlbumComponent } from '../../components/home/app-home.component';

const ROUTES: Route[] = [
  { path: '', component: LoginComponent},
  { path: 'albums', component: AlbumComponent }
  { path: 'photos', loadChildren: './photos/photos.module#PhotosModule' }

]

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    AlbumComponent
  ],
  imports: [
    ...
    RouterModule.forRoot(ROUTES)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
PreviousChange DetectionNextPreloading

Last updated 5 years ago