问题
I have updated my angular app into PWA, since I need to preload all of the assets on the first launch (application have a lots of images, which are used for UI). That's why I would like to show some kind of spinner/loading bar during service worker install event and hide it when it's done. So first question - is it possible to handle this event from the component?
I have found this example and tried to add it inside first component, that loads on app launch, but didn't get any logs. So probably it doesn't work that way.
ngOnInit() {
self.addEventListener('install', event => {
this.log("INSTALLING ");
const installCompleted = Promise.resolve()
.then(() => this.log("INSTALLED"));
event.waitUntil(installCompleted);
});
self.addEventListener('activate', event => {
this.log("ACTIVATING");
const activationCompleted = Promise.resolve()
.then((activationCompleted) => this.log("ACTIVATED"));
event.waitUntil(activationCompleted);
});
self.addEventListener('fetch', event => {
this.log("HTTP call intercepted - " + event.request.url);
return event.respondWith(fetch(event.request.url));
});
}
log(message) {
console.log(message);
}
Also I have a question about caching assets. In my ngsw-config.json I'm using next setup:
"name": "assets",
"installMode": "prefetch",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**"
]
}
but when I'm opening first page, in cache it doesn't show all the images and folder from /assets. Not event half of them. Is it ok and it's not supposed to show all the images that are cached? Is it possible that the problem is because I'm using lazy loading modules and service worker start caching when each module is loaded? On other hand, when I'm switching pages, in Network tab it shows that each image is loaded from service worker...
Thanks
回答1:
You can enhance your Angular service worker behaviour using the technique described here (link broken):
http://jakubcodes.pl/2018/06/13/enhancing-angular-ngsw/
It basically registers an intermediate script file as the service worker JavaScript file and in this, the Angular script besides own code is called.
Edit
The process in detail:
- Create two js files in your src folder (e.g. "sw-master.js" and "sw-custom.js"). The latter may contain your custom service worker code.
Add these two lines to your "sw-master.js" (import the custom script before the NGSW script):
importScripts('./sw-custom.js'); importScripts('./ngsw-worker.js');
Register the two new assets in the "angular.json" file of your project:
"assets": [ "src/favicon.ico", "src/assets", "src/manifest.json", "src/sw-master.js", "src/sw-custom.js" ],
Register the master script instead of "ngsw-worker.js" in your "app.module.ts":
ServiceWorkerModule.register('/sw-master.js', { enabled: environment.production })
来源:https://stackoverflow.com/questions/55256689/check-service-worker-installation-progress-from-component-angular