I have attached install event to service worker as below. But Install event fired before register event is completed. See code snippets and console logs below.
My concern is how install event is fired before register event is completed?
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./service-worker.js',{scope : '/'}).then(function(registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}).catch(function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
}
var cacheName = 'V-1';
var filesToCache = [
'/', '/index.html',
'/css/all.css', '/css/material.min.css',
'/js/all.js', '/js/material.min.js',
'/images/service-worker-1.png','/images/service-worker-2.png','/images/service-worker-3.png',
];
self.addEventListener('install', function(e) {
console.log('[ServiceWorker] Installing');
e.waitUntil(
caches.open(cacheName).then(function(cache) {
console.log('[ServiceWorker] Caching app shell');
return cache
.addAll(filesToCache) //this is atomic in nature i.e. if any of the file fails the entire cache step fails.
.then(() => {console.log('[ServiceWorker] App shell Caching Successful');})
.catch(() => {console.log('[ServiceWorker] App shell Caching Failed');})
})
);
});
navigator.serviceWorker.register()
is not an event. It's a function that returns a promise, and then promise will resolve with aServiceWorkerRegistration
object that corresponds to the registration.The actual service worker logic is executed in a different thread/process, and the lifecycle events that the service worker handles, like the
install
event, happen independently of the web page that registered the service worker. What you're seeing in yourconsole.log()
output is expected.If you want to keep track of the state of the service worker from your web page, you can add event listeners to the
ServiceWorkerRegistration
object. There's an example of this at https://googlechrome.github.io/samples/service-worker/registration-events/index.htmlIf you want to write code that will cause your web page to wait until there's an active service worker before it takes some action, you could make use of the
navigator.serviceWorker.ready
promise.