← Back to JavaScript Course | Chapter 9: Async & Web APIs | Lesson 9 of 26

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?

javascript
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

javascript
// 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

javascript
// 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

javascript
// 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

javascript
if ("serviceWorker" in navigator) {
  navigator.serviceWorker.register("sw.js");
}
console.log("PWA features rely on this registration.");

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.