Skip to content

Commit

Permalink
Switch to a network-then-cache strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
domenic committed Dec 29, 2016
1 parent 7e7832e commit 0061e69
Showing 1 changed file with 14 additions and 15 deletions.
29 changes: 14 additions & 15 deletions service-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,23 +21,22 @@ self.onfetch = e => {
}

e.respondWith(
caches.match(e.request).then(cachedResponse => {
// Respond with the cached response if it exists, but still do the network fetch in order to refresh the cache.
// Ignore network fetch errors; they just mean we won't be able to cache.
const networkFetchPromise = fetch(e.request).then(refreshCacheFromNetworkResponse).catch(() => {});

return cachedResponse || networkFetchPromise;
// Since this is a Living Standard, it is imperative that you see the freshest content, so we use a
// network-then-cache strategy.
fetch(e.request).then(res => {
if (!res.ok) {
throw new Error(`${res.url} is responding with ${res.status}; falling back to cache if possible`);
}
})
.then(res => {
const responseForCache = res.clone();
// Do not return this promise; it's OK if caching fails, and we don't want to block on it.
caches.open(cacheKey).then(cache => cache.put(e.request, responseForCache));
})
.catch(() => {
return caches.match(e.request);
})
);

function refreshCacheFromNetworkResponse(response) {
const responseForCache = response.clone();

// Ignore any errors while caching.
caches.open(cacheKey).then(cache => cache.put(e.request, responseForCache));

return response;
}
};

self.onactivate = e => {
Expand Down

0 comments on commit 0061e69

Please sign in to comment.