Revision 4502480240801eb26c1834728471d939e61c385b authored by Luke Bjerring on 05 April 2018, 15:35:55 UTC, committed by Luke Bjerring on 05 April 2018, 15:35:55 UTC
1 parent 08906cb
Raw File
register-and-activate-service-worker.js
async function registerAndActiveServiceWorker(script, scope, callback) {
  const registration = await navigator.serviceWorker.register(script, {scope});
  const serviceWorker =
    registration.installing || registration.waiting || registration.active;
  if (serviceWorker) {
    waitForServiceWorkerActivation(scope, callback);
    return;
  }

  registration.addEventListener('updatefound', event => {
    waitForServiceWorkerActivation(scope, callback);
  });
}

async function waitForServiceWorkerActivation(scope, callback) {
  const registration = await navigator.serviceWorker.getRegistration(scope);
  if (registration.active) {
    callback(registration);
    return;
  }

  const serviceWorker = registration.installing || registration.waiting;
  serviceWorker.addEventListener('statechange', event => {
    if (event.target.state == 'activated') {
      callback(registration);
    }
  });
}
back to top