JS Service Workers
What Is a Service Worker?
A service worker is a background browser script that can handle requests and support offline caching. It normally needs HTTPS or localhost. Because it can intercept and respond to network requests even without a page open, it enables offline support and background functionality regular scripts can't provide.
Example: What Is a Service Worker?
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("sw.js")
.then(() => console.log("Service worker registered"));
}
Install Event
The install event runs when a service worker is installed. It is often used to prepare cached resources. This is a common place to pre-cache the static assets an app needs so they're available even before the first network request completes.
Example: Install Event
// sw.js
self.addEventListener("install", (event) => {
console.log("Installing, ready to pre-cache assets");
});
Cache Storage
The Cache API lets a service worker store responses for later use. The Cache API works alongside fetch() to store and later retrieve responses, forming the foundation of most offline-first caching strategies.
Example: Cache Storage
// sw.js
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open("v1").then((cache) => cache.addAll(["/", "/style.css"]))
);
});
Fetch Event
A service worker can intercept network requests with the fetch event. Intercepting fetch lets the service worker decide whether to serve a cached response, go to the network, or apply some combination of both depending on the request.
Example: Fetch Event
// sw.js
self.addEventListener("fetch", (event) => {
event.respondWith(
caches.match(event.request).then((cached) => cached || fetch(event.request))
);
});
Practical Use
Service workers can support offline pages, caching strategies, and progressive web app features. These capabilities are what make Progressive Web Apps possible — installable, offline-capable experiences built with regular web technologies.
Example: Practical Use
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("sw.js");
}
console.log("PWA features rely on this registration.");
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS JSON
- JS Regular Expressions
- JS Fetch API
- JS LocalStorage and SessionStorage
- JS Cookies
- JS setTimeout and setInterval
- JS Event Loop
- JS Web Workers
- JS Service Workers
- JS AJAX
- JS AJAX Intro
- JS AJAX XMLHttp
- JS AJAX Request
- JS AJAX Response
- JS AJAX XML
- JS AJAX PHP
- JS AJAX Database
- JS JSONP
- JS RegExp Flags
- JS RegExp Classes
- JS RegExp Metachars
- JS RegExp Assertions
- JS RegExp Groups
- JS RegExp Quantifiers
- JS JSON HTML
- JS JSON vs XML