Lazy Loading in Ionic 3

What is Lazy Loading?
  • Angular is a one page app.
  • Without lazy loading, all pages are loaded at the start of the app. With lazy loading, a page is loaded only when it is needed.
  • Therefore, for app with many pages, lazy loading allows faster initial load of the app, which should give better user experience.
How to do it in Ionic 3?

Briefly

  1. Add “@IonicPage()” decorator in every lazy-loaded page
  2. Create a module file, which imports “IonicPageModule”
  3. This page is not imported from anywhere. It is referred by calling its name as string
    e.g. navCtrl.push(‘ComponentName’) instead of navCtrl.push(ComponentName)

In more details

When a page has @IonicPage() decorator, the compiler knows that the page is a lazy-loaded page. For example, I have BookingPage defined in booking.ts


import { IonicPage } from 'ionic-angular';
...
@IonicPage()
@Component({
  selector: 'page-booking',
  templateUrl: 'booking.html'
})
export class BookingPage {
  ...
}

The compiler knows that the above is a lazy loaded page. The compilation will automatically look for booking.module.ts, which imports
IonicPageModule.forChild(BookingPage). So we need to create the module like that below.


import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { BookingPage } from './booking';
...

@NgModule({
  declarations: [
    BookingPage,
    ...
  ],
  imports: [
    IonicPageModule.forChild(BookingPage),
    ...
  ],
  exports: [
    BookingPage,
    ...
  ]
})
export class BookingPageModule { }

Both the above booking.ts and booking.module.ts are not imported from anywhere. They are linked in the project internally by Ionic 3. We just need to have those two files.

As BookingPage is not imported from anywhere, how do we show it? It’s by calling its name as string. For example when it is to be shown using a navigation controller, we call:

navCtrl.push('BookingPage')

instead of

navCtrl.push(BookingPage)

As usual, nothing new here, many people have done this. Just my note. Have a great day!

Leave a Reply

Your email address will not be published. Required fields are marked *