Skip to content

Instantly share code, notes, and snippets.

@Akash52
Last active May 30, 2023 20:39
Show Gist options
  • Save Akash52/6f5eacad6d535da22e25d33e63d2e5a7 to your computer and use it in GitHub Desktop.
Save Akash52/6f5eacad6d535da22e25d33e63d2e5a7 to your computer and use it in GitHub Desktop.
serviceworker.js file for react
//This is a service worker script that caches specific URLs for offline use and handles network requests when the internet connection is not available.
// We give a name to our cache, so we can refer to it later.
const CACHE_NAME = "version-1";
// These are the URLs that we want to cache.
const urlsToCache = ["index.html", "offline.html"];
// We call the 'self' object, which refers to the Service Worker itself.
const self = this;
// This event listener gets triggered when the Service Worker is being installed on the user's device.
self.addEventListener("install", (event) => {
// We wait until a cache storage is opened with the given name.
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
console.log("Opened Cache"); // We log a message to the console when the cache storage is opened successfully.
return cache.addAll(urlsToCache); //We add the specified URLs to the cache storage.
})
);
});
// This event listener listens for fetch events (i.e., requests for data from the Internet).
self.addEventListener("fetch", (event) => {
event.respondWith(
// First, we check if the requested resource is already in the cache storage.
caches.match(event.request).then(() => {
// If it is in the cache storage, we return that cached version of the resource.
return fetch(event.request).catch(() => caches.match("offline.html"));
})
);
});
// This event listener gets triggered when the Service Worker is activated.
// It clears old caches that are not included in the cachesWhitelist array, so that the Service Worker doesn't take up too much storage space.
self.addEventListener("activate", (event) => {
const cachesWhitelist = [];
cachesWhitelist.push(CACHE_NAME);
event.waitUntil(
// We check all the cache storages that are currently open.
caches.keys().then((cacheNames) =>
Promise.all(
cacheNames.map((cacheNames) => {
if (!cachesWhitelist.includes(cacheNames)) { // If the cache storage is not included in the whitelist, we delete it.
return caches.delete(cacheNames);
}
})
)
)
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment