Lazy loading in ionic angular framework

Nothing strikes fear into the hearts of developers quite like being told their app is slow. Because of this, great pains are taken to optimize the loading and startup performance in our apps. The techniques we use have changed over the years, but the good news is that a lot of the heavy lifting is now done for us by our frameworks and build systems.

In this post, we will take a look at how lazy loading can be used to help speed up the load times of your Ionic Angular apps. Also, it doesn’t matter if your app is packaged and downloaded from the store, or a progressive web app (PWA) running off a server, lazy loading can help increase your startup times in both situations.


Why Optimize Loading Performance?
Performance is about letting users do what they need to do with your app as quickly and efficiently as possible. If your app is slow to load or unresponsive, then your customers will quickly leave and find an app that works better.

Over the past several years, web sites have started to become more app-like by offering better experiences and more functionality. As apps have become more complex, the amount of JavaScript needed to be downloaded has increased as well. JavaScript is the most expensive asset to download, so this dramatic increase in size now posed a new dilemma for our web apps.

To counter these larger bundle sizes, there are now a few additional techniques we can use to help our apps stay fast. One of these techniques is lazy loading, which breaks larger JavaScript bundles up into smaller chunks and delivers them to the browser as needed. Let’s see how we can begin to optimize our loading performance in an Ionic Angular app.


Note, it is known that premature optimization is the root of all evil. What we will go over are particular techniques you can use to see if it helps your apps, but these aren’t one-size-fits-all rules to throw at every project. Take the time to build out your app and then go over these options to see if they can point you in the right direction and are a good fit for your goals.

Lazy Loading in Ionic Angular
The idea behind lazy loading is that we only download the HTML, CSS, and JavaScript that our application needs to render its first route, and then load additional pieces of our application as needed. The great news is that a new Ionic Angular 4.0 app has lazy loading configured by default. Lazy loading is expressed through how the Angular routes are setup:

*const routes: Routes = [
  {
    path: '',
    loadChildren: './tabs/tabs.module#TabsPageModule'
  }
];*

This is the initial route that is created for you when starting a new Ionic app using the tabs starter template. By specifying a loadChildren string (instead of passing a page class to component), the Angular router will load this file dynamically when the user navigates to the route. This JavaScript also gets split off from the rest of the app into its own bundle.

Below, we have the routes setup in the tabs routing module:

const routes: Routes = [
  {
    path: 'tabs',
    component: TabsPage,
    children: [
      {
        path: 'tab1',
        children: [
          {
            path: '',
            loadChildren: '../tab1/tab1.module#Tab1PageModule'
          }
        ]
      },
      /// tab 2, tab3...
  }
]
Each tab in this configuration loads its children lazily as well, meaning all the files for tab2 are not loaded until the user navigates to the tab2 page.

By breaking apart our app into separate lazily loaded chunks, we make it so that the browser doesn’t need to download, parse, and compile our entire app before the user even interacts with the first page. If our app was of significant size, this would greatly increase the initial load time of the app.

Using lazy loading can help your app load fast, however, if a user navigates to a new page, the assets will still need to be downloaded before the user views the page. There can be a small delay while this download happens, and it could be several seconds if on a slow network, giving your app a sluggish feel.

But lazy loading was supposed to make our app fast! Well, it did, at least for the initial page load. Now, let’s take a look at how to pre-load additional routes so they are available when the user wants them.

Optimizing Lazy Loading
When importing the Router module in the main app module, you can specify a pre-loading strategy to use. There are two that come out of the box with Angular:

NoPreloading: Does not perform any preloading of lazily loaded modules. This is the default behavior if no strategy is specified.
PreloadAllModules: After your app loads the initial module, this strategy will preload all the rest of the modules when the network becomes idle. In the Ionic starter templates, we set this option for you automatically.
To specify which strategy to use, set the preloadingStrategy parameter on the options object when setting up the router in app-routing.module.ts:

@NgModule({
    imports: [
      RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
    ],
    exports: [RouterModule]
})
The preloadAllModules strategy essentially loads the rest of the app in memory after the first route loads. Navigating between pages will now be quick, as all the routes and modules are loaded and ready to go.

While preloadAllModules is a sensible default for most apps, if your app is large enough, loading the entire thing might not be the best option. You might waste user’s bandwidth (if your app is a PWA) by downloading screens they might not visit. Your initial load might also be slower using preloadAllModules if your app is so large that it takes considerable time to parse and compile the JavaScript.

Fortunately, we can also define custom pre-loading strategies in Angular. Let’s take a look at how to set this up next. 

Related blogs:

[Spring MVC interview questions and answers](http://candidjava.com/tutorial/spring-mvc-rest-interview-questions-and-answers/)

More about [Lazyloading](https://blog.ionicframework.com/how-to-lazy-load-in-ionic-angular/)