'angular lazy loading service worker prefetch
I realized that using lazy loading loses the major
feature of a pwa if the user does not visit the page
you do not have the possibility of offline browsing.
So is there a way to prefetch the lazy loading files ?
Solution 1:[1]
Yes, you need to define the pre-loading strategy:
imports: [RouterModule.forRoot(ROUTES, {preloadingStrategy: PreloadAllModules})]
See http://recurship.com/blog/2017/9/30/introduction-to-angular-router-lazy-loading-and-prefetchin for more details
CUSTOM PRELOADING STRATEGY:
You can also preload some and not others with a custom preload strategy.
import 'rxjs/add/observable/of';
import { Injectable } from '@angular/core';
import { PreloadingStrategy, Route } from '@angular/router';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class CustomPreloadingStrategy implements PreloadingStrategy {
preloadedModules: string[] = [];
preload(route: Route, load: () => Observable<any>): Observable<any> {
if (route.data && route.data['preload']) { // see app.routing.ts
this.preloadedModules.push(route.path);
return load();
} else {
return Observable.of(null);
}
}
}
Then in app.module.ts:
@NgModule({
imports: [RouterModule.forRoot(routes, { preloadingStrategy:
CustomPreloadingStrategy })],
exports: [RouterModule],
providers: [CustomPreloadingStrategy]
})
app.routing.ts:
{
path: ':section',
loadChildren: './gm-email/gm-email.module#GmEmailModule',
data: { preload: true }
}
Basically, if data.preload is true you are saying preload this one immediately AFTER the app has loaded (i.e. AFTER the first module has lazy loaded) ELSE preload it on demand (i.e. when the user clicks a link lazy load it)
Solution 2:[2]
In the Angular service worker file ngsw-config.json, setting installMode to prefetch and specifying /*.js in the resources.files array will instruct the Angular service worker to prefetch your lazy loading .js bundles when the PWA is installed without losing the benefit of lazy loading if your user is navigating online in a browser.
Example:
"$schema": "./node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/manifest.webmanifest",
"/*.css",
"/*.js"
]
}
}
]
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Touré Holder |
