Re: [w3c/ServiceWorker] registration.ready promise (#770)

It would be also useful if there were a way to wait for a *specific* worker to become active. (If, for example, you have versioned your service worker (and JS, CSS, etc.) and your HTML depends on a particular version.)

I think the following accomplishes this, though I keep finding edge cases I've missed:

```js
function registerReady(script, options) {
  return navigator.serviceWorker.register(script, options).then(r => {
    const incoming = r.installing || r.waiting;
    if (r.active && !incoming) {
      return r;
    }
    return new Promise(resolve => {
      const l = e => {
        if (e.target.state === 'activated' || e.target.state === 'redundant') {
          incoming.removeEventListener('statechange', l);
          if (e.target === navigator.serviceWorker.controller) {
            resolve(r);
          }
        }
      };
      incoming.addEventListener('statechange', l);
    });
  });
}
```

It can be used as a direct replacement for `navigator.serviceWorker.register()`:

```js
// Resolves when '/sw.06fdc991c6a4.js' is active *and* controlling the page (maybe never)
const reg1 = registerReady('/sw.06fdc991c6a4.js', options);
```

To contrast with some other options:

```js
// Resolves when browser starts executing '/sw.06fdc991c6a4.js'
const reg2 = navigator.serviceWorker.register('/sw.06fdc991c6a4.js', options);

// Resolves when (some) service worker is active (may not be controlling the page)
const reg3 = navigator.serviceWorker.ready;

// Resolves when '/sw.06fdc991c6a4.js' is active (may not be controlling the page)
const reg4 = regReady(reg2); // as above
```


-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/w3c/ServiceWorker/issues/770#issuecomment-251939417

Received on Thursday, 6 October 2016 11:48:28 UTC