Ionic Angular Preload Modules Only on Device

Ionic Angular application has lazy loading configured by default. It works well, but if the app is very large preloading every module in the background may cause unnecessary data to be loaded in the background. You might waste user’s bandwidth by downloading screens they might not visit. Ideally, for mobile web, we would like to preload the core features only to keep the bundle small. However, on mobile devices, it should preload all the rest of the modules when the network becomes idle because all the connections are on local without using any real bandwidth.

Fortunately, It is possible with Ionic’s Platform and Angular PreloadingStrategy. We can define custom pre-loading strategy in Angular and detect the platform using Ionic’s Platform Service. 

To create a strategy, Angular provides an abstract class called PreloadingStrategy that you can implement. This class has one method you need to override, preload, which takes in the configured lazy route, and a parameterless function you can call to programmatically load the lazy route. It returns an observable of type any. A better strategy can be created by utilizing this class.

import { Injectable } from '@angular/core';
import { PreloadingStrategy, Route } from '@angular/router';
import { Observable, of } from 'rxjs';
import { Platform } from '@ionic/angular';

@Injectable({
    providedIn: 'root'
})
export class LocalOnlyPreloadingStrategy implements PreloadingStrategy {
    constructor(private platform: Platform) { }
    public preload(route: Route, fn: () => Observable<boolean>): Observable<boolean> {
        console.log(this.platform.is('hybrid'), route);
        if (this.platform.is('hybrid')) {
            // Running on a device
            return fn();
        }
        // Not running on a device
        return of(false);
    }
}

LocalOnlyPreloadingStrategy does exactly what PreloadAllModules does on the device but does exactly what NoPreloading does on the web. This gives the app optimum agility in all platforms.

You can simply import and use just like in your code;

import { LocalOnlyPreloadingStrategy } from './services/local-only-preloading-strategy.service';

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { useHash: true, preloadingStrategy: LocalOnlyPreloadingStrategy })
  ],
  exports: [RouterModule],
  providers: [LocalOnlyPreloadingStrategy]
})
export class AppRoutingModule { }

For more information;