Topic 006: Service workers in JS
A Service Worker is a script that runs in the background of the browser, separate from the web page, enabling features that don’t need a web page or user interaction. These features include handling network requests, caching assets, and enabling push notifications. Service Workers are a key component of Progressive Web Apps (PWAs).
To use a Service Worker, you must register it in your web page’s JavaScript code. The registration process tells the browser where your Service Worker script is located.
if ("serviceWorker" in navigator) {
window.addEventListener("load", () => {
navigator.serviceWorker
.register("/service-worker.js")
.then((registration) => {
console.log("ServiceWorker registration successful with scope: ", registration.scope);
})
.catch((error) => {
console.log("ServiceWorker registration failed: ", error);
});
});
}
The Service Worker script handles various events like install
, activate
, and fetch
.
service-worker.js
const CACHE_NAME = "my-cache-v1";
const urlsToCache = ["/", "/styles/main.css", "/script/main.js"];
// Install event
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
console.log("Opened cache");
return cache.addAll(urlsToCache);
})
);
});
// Activate event
self.addEventListener("activate", (event) => {
const cacheWhitelist = [CACHE_NAME];
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
});
// Fetch event
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
// Cache hit - return the cached response
if (response) {
return response;
}
return fetch(event.request).then((response) => {
// Check if we received a valid response
if (!response || response.status !== 200 || response.type !== "basic") {
return response;
}
// Clone the response
const responseToCache = response.clone();
caches.open(CACHE_NAME).then((cache) => {
cache.put(event.request, responseToCache);
});
return response;
});
})
);
});
Install Event:
urlsToCache
) to it.Activate Event:
Fetch Event:
By leveraging Service Workers, you can create more resilient, faster, and offline-capable web applications.