service worker install event is called before register event is completed

我们两清 提交于 2019-12-08 04:03:54

问题


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');})
    })
  );
});


回答1:


navigator.serviceWorker.register() is not an event. It's a function that returns a promise, and then promise will resolve with a ServiceWorkerRegistration 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 your console.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.html

If 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.



来源:https://stackoverflow.com/questions/40902060/service-worker-install-event-is-called-before-register-event-is-completed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!