Skip to content

Instantly share code, notes, and snippets.

@tuxracer
Created October 13, 2016 20:49
Show Gist options
  • Save tuxracer/c1d78ad07b5f73280e14d78b27eca3ab to your computer and use it in GitHub Desktop.
Save tuxracer/c1d78ad07b5f73280e14d78b27eca3ab to your computer and use it in GitHub Desktop.
var version = 'app-v1';
var expectedCaches = [version];
self.oninstall = () => console.log('Installed version:', version);
self.onfetch = (event) => {
event.respondWith(
// Check cache for request
caches.match(event.request)
.then((cachedResponse) => {
// If we have a cached response return it immediately unless this is an API request.
// For those we'll only fallback to a cached response as a last resort
if (cachedResponse &&
cachedResponse.type !== 'error' &&
!event.request.url.match('/api|jsonp')
) {
console.log('Returning cached response ' + event.request.url, cachedResponse);
return cachedResponse;
}
// Try to make the request
return fetch(event.request.clone())
.then((response) => {
if (!response || response.status !== 200) {
throw new Error('Invalid response ' + event.request.url);
}
return response.clone();
})
.then((response) => {
const clonedRequest = event.request.clone();
const clonedResponse = response.clone();
// Cache the response
caches.open(version).then((cache) => cache.put(clonedRequest, clonedResponse));
// Return the live response
console.log("Returning live response for", event.request.url);
return response;
}, (err) => {
// Fallback to cached response if request fails
return cachedResponse;
});
})
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment