Re: [whatwg/streams] Meta: add a service worker to the spec (#637)

jakearchibald approved this pull request.



> +        const networkFetchPromise = fetch(e.request);
+
+        // Ignore network fetch or caching errors; they just mean we won't be able to refresh the cache.
+        networkFetchPromise
+          .then(res => refreshCacheFromNetworkResponse(e.request, res))
+          .catch(() => {});
+
+        return cachedResponse || networkFetchPromise;
+      })
+    );
+  }
+};
+
+self.onactivate = e => {
+  e.waitUntil(caches.keys().then(keys => {
+    return Promise.all(keys.filter(key => key !== cacheKey).map(key => caches.delete(key)));

I'm guessing this will be the only service worker on this origin? A more general solution might not be able to assume this.

> +};
+
+self.onactivate = e => {
+  e.waitUntil(caches.keys().then(keys => {
+    return Promise.all(keys.filter(key => key !== cacheKey).map(key => caches.delete(key)));
+  }));
+};
+
+function refreshCacheFromNetworkResponse(req, res) {
+  if (!res.ok) {
+    throw new Error(`${res.url} is responding with ${res.status}`);
+  }
+
+  const resForCache = res.clone();
+
+  // Do not return this promise; it's OK if caching fails, and we don't want to block on it.

You could pass it to `fetchEvent.waitUntil` - it doesn't delay the return of the response to the browser, but it ensures the SW is kept awake until caching is complete.

We updated the spec so `waitUntil` could be called async, but it hasn't landed in browsers yet. Polyfill: https://github.com/jakearchibald/async-waituntil-polyfill

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/streams/pull/637#pullrequestreview-15122460

Received on Wednesday, 4 January 2017 14:50:17 UTC