Service Workers in JavaScript

Cache a page in JavaScript with service-worker install and fetch handlers on HTTPS or localhost. Use three files and reload online before testing offline.

AdvancedJavaScript Browser APIsExample 7 of 15

Create index.html, app.js, and sw.js from the labelled sections. They are separate files, not one script. Serve this practice folder on HTTPS or localhost.

service-workers.js
1// Three files in the same folder. Serve them on HTTPS or localhost.
2// index.html:
3// <button id="setup">Enable offline page</button><p id="status"></p>
4// <script src="app.js"></script>
5
6// app.js:
7document.querySelector('#setup').onclick = async () => {
8 const status = document.querySelector('#status');
9 if (!('serviceWorker' in navigator)) { status.textContent = 'Service workers not supported.'; return; }
10 try {
11 await navigator.serviceWorker.register('./sw.js');
12 await navigator.serviceWorker.ready;
13 status.textContent = 'Offline page ready. Reload once while online, then try offline.';
14 } catch { status.textContent = 'Setup failed. Check HTTPS, paths, and console errors.'; }
15};
16
17// sw.js (save the following section in a separate file):
18const CACHE = 'revision-offline-v1';
19self.addEventListener('install', event => {
20 event.waitUntil(caches.open(CACHE).then(cache => cache.addAll(['./', './app.js'])));
21});
22self.addEventListener('fetch', event => {
23 if (event.request.method !== 'GET' || new URL(event.request.url).origin !== self.location.origin) return;
24 event.respondWith(caches.match(event.request).then(saved => saved || fetch(event.request)));
25});

Sample Output

Offline page ready. Reload once while online, then try offline.

The worker is active after its install caching work. A later navigation brings this page under its control.

In this one

  • Register a separate worker file
  • Cache a small page during install
  • Return a cached response
  • Test offline only after setup

How it works

  1. 1

    Split the labelled sections into index.html, app.js, and sw.js.

  2. 2

    Serve the folder on localhost or HTTPS and click Enable offline page.

  3. 3

    During installation, wait for both listed files to be cached.

  4. 4

    For same-origin GET requests, try the cache before the network.

  5. 5

    Reload online once, then switch the browser offline and reopen the cached page.

Edge cases

file:// URL

Double-clicking the HTML file will not provide the needed worker setup.

Use a local web server. Keep sw.js beside the page so it can control pages in that folder.

Old cached content

Cache-first can keep returning an older file.

For later edits, change the cache version and add old-cache cleanup in an activate handler, or unregister and clear storage while learning.

What's going on

A service worker is a separate browser script that can handle requests for pages and files. It can save copies of files so a small revision page can open without a network connection. Registration alone does not make a page work offline; the worker must actually save and return files.

This browser-only example needs three files: index.html with the shown button and script tag, app.js with the page handler, and sw.js with the worker section. Serve the folder on HTTPS or localhost, not by double-clicking a file. Click the button while online. The install handler saves the folder page and app.js in a named cache, which is storage for request-and-response pairs.

The fetch handler returns a saved response when one exists and otherwise uses the network. Reload once online so the page is controlled by the installed worker, then test offline. This small lesson uses saved files first. It is not a complete offline app. It does not save every future request, refresh changed files, or cache private account data. Use a dedicated test folder and remove the worker in browser developer tools when finished.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What keeps install waiting for caching?

Pick an answer to check it.

Question 2

What happens to an uncached file offline?

Pick an answer to check it.

Questions people ask

Why do I need sw.js?

The browser loads a service worker as a separate script. It is not an ordinary function in the page.

Does this cache my whole website?

No. Installation saves only the folder page and app.js. Requests not found there still need the network.

Why reload before the offline test?

The first page can load before the new worker controls it. A later navigation normally brings it under control.