Ionic 3 - Lazy loading modules -- Words (424)

Ionic
Ionic 3 - Lazy loading modules

Lazy loading refers to the process of loading chunks of code (such as a component ,directive or pipe ) when it's requested not when the app is loading .The clearest and straight forward benefit of lazing loading is the increased performance especially when the app is starting .

To demonstrate how we can lazy load a component or page ,lets take a new project based on the blank template .

ionic start lazy-loading-demo blank 

Navigate inside the project directory and open it with your prefered IDE/Code Editor .I'm using Visual Studio Code .

code .

Open src/app/app.module.ts

@NgModule({
declarations: [
    MyApp,
    HomePage  
    ],
imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
    MyApp,
    HomePage
],
providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}

You can see ,there are two components in the declarations and entryComponents arrays ,this means that we are importing two components into our module.

Now lets lazy load the HomePage component so it can be loaded only when it's requested .

First of all ,remove all references to HomePage from our app module including the import statement .

Next ,we need to give HomePage its own NgModule ,so create a new file src/pages/home/home.module.ts

import { NgModule } from [email protected]/core';
import { IonicPageModule } from 'ionic-angular';
import { HomePage } from './home';

@NgModule({
declarations: [
    HomePage,
],
imports: [
    IonicPageModule.forChild(HomePage),
],
exports: [
    HomePage
]
})
export class HomePageModule {}
You can also just remove home page and re-generate it using the CLI
ionic g page HomePage
A new page with its own NgModule will be generated .

Next add @IonicPage() decorator to HomePage .

import { IonicPage } from 'ionic-angular';

@IonicPage()
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {

The last thing you need to do to lazy load HomePage page is going to src/app/app.component.ts.

Remove the import statement of HomePage ,then remove the reference to HomePage and replace it with the string containing name of the page i.e 'HomePage' .

export class MyApp {
rootPage:any = 'HomePage';

Conclusion


So we have seen the process of lazy loading a page which is simply creating an NgModule for it and decorate it with an IonicPage decorator ,then reference it by a string of its name .




mrnerd is a Web Entrepreneur & Developer, Digital Marketer and a Passionate Blogger. He writes about software and website development,money making tips and SEO etc.. He is a tech addict and a computer geek with a lot of hobbies.