Revision f76a95c7dcfc4553b8bbc67cf20bcacf816997fa authored by Geoffrey Sneddon on 25 April 2018, 21:33:28 UTC, committed by Geoffrey Sneddon on 30 April 2018, 12:46:37 UTC
1 parent 0ef9a74
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