Skip to content

Instantly share code, notes, and snippets.

@arnav-kr
Last active April 11, 2022 07:42
Show Gist options
  • Save arnav-kr/0ad065605d2fe20967a6da383aef8b72 to your computer and use it in GitHub Desktop.
Save arnav-kr/0ad065605d2fe20967a6da383aef8b72 to your computer and use it in GitHub Desktop.
A Basic Service Worker Template with Explanations
// TODO: Update the cacheName Everytime you want to update your cache
const cacheName = "v1.0.0";
const cacheKeepList = [cacheName] // Add Other names of cache that you don't want to delete
// TODO: Add the default response URL
// When the User is offline and the requested resource is not in the cache then this response will be returned. This needs to be in the cache
defaultResponseURL = "";
// TODO: Add your resource's URLs that you want to precache
const preCacheURLs = [
defaultResponseURL,
// "./",
// "./favicon.png",
];
// Service Worker "install" event listener
self.addEventListener("install", (event) => {
event.waitUntil(
// Put the preCache resources in cache on install
caches.open(cacheName).then((cache) => {
return cache.addAll(preCacheURLs);
})
);
});
// Service Worker "activate" event listener
self.addEventListener("activate", (event) => {
event.waitUntil(
// Iterate over the Keys of Cache
caches.keys().then((keyList) => {
// Remove the Cache if the name is is not in the cacheKeepList
return Promise.all(keyList.map((key) => {
if (cacheKeepList.indexOf(key) === -1) {
return caches.delete(key);
}
}));
})
);
});
// Service Worker "fetch" event listener
self.addEventListener("fetch", (event) => {
// Respond to Fetch Request
event.respondWith(
// Find the resource in cache first
caches.match(event.request).then((resp) => {
// If found then return to user else do a network request
return resp || fetch(event.request).then((response) => {
// Clone the response from the network request
let responseClone = response.clone();
// Add the response in cache so that next time it can directly get from cache instead doing a network request
caches.open(cacheName).then((cache) => {
cache.put(event.request, responseClone);
});
// Now return the response to the user
return response;
}).catch(() => {
// In case of no network and requested resource not in cache, return a default / fallback response from cache
return caches.match(defaultResponseURL);
})
})
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment