Skip to content

Instantly share code, notes, and snippets.

@Himachallad
Created July 26, 2020 20:10
Show Gist options
  • Save Himachallad/da9e4ed60d91f2f42d606f7b6ed6ac6a to your computer and use it in GitHub Desktop.
Save Himachallad/da9e4ed60d91f2f42d606f7b6ed6ac6a to your computer and use it in GitHub Desktop.
async function updateCacheFromResponse(cache, request, fetchResponse) {
if (fetchResponse.status >= 200 && fetchResponse.status < 300) {
await cache.put(request, fetchResponse);
}
console.log("Cache updated");
}
/**
* Lazily updates cache in background from network
* @param {*} request
*/
async function updateCacheFromNetwork(request) {
try {
const cache = await caches.open(VOLATILE);
const fetchResponse = await fetch(request);
updateCacheFromResponse(cache, request, fetchResponse.clone());
} catch (err) {
console.log("Network call failed with error: ", err);
}
}
/**
* Network call made when we couldn't find request in the cache
* @param {*} request
*/
async function getResponseFromNetwork(request) {
const fetchResponse = await fetch(request);
const cache = await caches.open(VOLATILE);
updateCacheFromResponse(cache, request, fetchResponse.clone());
return fetchResponse;
}
/**
* The fetch handler serves responses for same-origin resources from a cache.
*
* If response is cached then return cached response and lazily update
* the cache in background
* else get response from network and cache the response for future
*
*/
self.addEventListener("fetch", (event) => {
// Skip cross-origin requests, like those for Google Analytics.
if (event.request.url.startsWith(self.location.origin)) {
event.respondWith(
caches.match(event.request).then(async (cachedResponse) => {
/**
* We want font and images to work in cache only mode.
*/
let destination = event.request && event.request.destination;
switch (destination) {
case "image":
case "font":
if (cachedResponse) {
return cachedResponse;
}
}
if (cachedResponse) {
updateCacheFromNetwork(event.request);
return cachedResponse;
} else {
const fetchedResponse = await getResponseFromNetwork(event.request);
return fetchedResponse;
}
})
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment