Created
March 19, 2019 09:12
-
-
Save danielpotthast/fef9a22e694d62e647fba27818da2e27 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
self.addEventListener("fetch", (event) => { | |
event.respondWith( | |
caches.match(event.request) | |
.then(response => { | |
if (response) { | |
return response; | |
} | |
// Version #1: Cache all (!) responses and return error page | |
// Clone the request | |
let fetchRequest = event.request.clone(); | |
return fetch(fetchRequest) | |
.then(response => { | |
// Check response | |
if (!response || response.status !== 200 || response.type !== 'basic') { | |
return response; | |
} | |
// Clone the response | |
let responseToCache = response.clone(); | |
caches.open(CACHE_VERSION) | |
.then(cache => { | |
cache.put(event.request, responseToCache); | |
}); | |
return response; | |
}) | |
.catch(() => { | |
return caches.match(OFFLINE_URL); | |
}); | |
// Version #2: Return error page | |
return fetch(event.request) | |
.catch(() => { | |
return caches.match(OFFLINE_URL); | |
}); | |
}) | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment