[w3c/ServiceWorker] Provide a one-line way to listen for a waiting Service Worker (#1222)

It's a common use case to pop up a notification to end users when a new Service Worker is waiting, but it's inconvenient to listen for that event.

ServiceWorkerRegistration offers an `onupdatefound` event, but that fires when the new Service Worker is detected and installation has _started_, not when the new Service Worker is fully installed and waiting to take control. In other words, it notifies us when `registration.installing` changes, but not when `registration.waiting` changes.

It's still possible to await a change in `registration.waiting` by attaching a listener to the `onstatechange` event of the `.installing` Service Worker, and to wait for an `.installing` Service Worker by waiting for the `onupdatefound` event of the registration itself, like this:

```js
function listenForWaitingServiceWorker(reg, callback) {
  function awaitStateChange() {
    reg.installing.addEventListener('statechange', function() {
      if (this.state === 'installed') callback(reg);
    });
  }
  if (reg.waiting) return callback(reg);
  if (reg.installing) return awaitStateChange();
  reg.addEventListener('updatefound', awaitStateChange);
}
```

This function gets its own special quiz in the Udacity "Offline Web Applications" course; it seems like this cow path could be paved.

I propose adding an `onwaiting` event to ServiceWorkerRegistration, and/or a `.waiting` Promise on the ServiceWorkerContainer. I'd love a one-liner like this:

```js
navigator.serviceWorker.waiting().then(alertUser);
```

-- 
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/1222

Received on Monday, 13 November 2017 09:04:07 UTC