Skip to content
Language:en Author:Laborci Gergely
web-apps

Service workers and offline operation

Objectives

By the end of the lesson, you can say what a service worker is, what it can and cannot do, how the Cache API differs from IndexedDB, and you can state precisely what works offline in an application.

Why do we need a background component?

The network of a web application can drop: on a train, in a lift, with weak coverage. A traditional page then shows a "no connection" error. If, however, the application has stored the necessary resources in advance, and there is a component that can answer network requests locally too, some things can work without a network. This is the task of the service worker.

Course material on the way

A student on a train would open a course description seen earlier, but the connection drops. If the application stored the necessary HTML, styles, and other resources in advance, the service worker can answer certain requests from these. The student can thus read the material that was made available earlier. The fresh number of places or a new enrolment, however, cannot reliably be regarded as final without the network and a server-side decision.

flowchart TD
    O[Page requests a resource] --> W[Service worker]
    W -->|a suitable local response exists| C[Cache]
    W -->|network needed| N[Server]
    C --> O
    N --> O

The diagram shows one possible operation. The service worker does not control every request of every page, and the actual path is determined by the caching strategy of the application.

What is a service worker?

According to MDN, a service worker is an event-driven component registered for an origin and a path, which acts as a proxy between the web application, the browser, and the network. Its properties:

  • A separate thread: it has no direct access to the DOM; the visible interface is still handled by the page.
  • Event-driven: it reacts to events such as install, activate, and fetch (intercepting a request and determining the response to it).
  • Scope: it applies to the whole origin or a part of it, which can be given at registration.
  • Secure context: it requires HTTPS (localhost is an exception), because such a component could intercept requests.
  • Lifecycle: in the install event the cache is typically filled; a new version is installed in a "waiting" state, and activates only when no page is controlled by the old version any more; the activate event serves to clean up old caches.

Because the lifecycle is separate, a new application version together with old cached content can easily cause errors if there is no consistent refresh plan.

A short sketch of the fetch event (illustrative, not run, because it needs a browser and HTTPS or localhost):

self.addEventListener("fetch", (esemeny) => {
  esemeny.respondWith(
    caches.match(esemeny.request).then((talalat) => talalat || fetch(esemeny.request))
  );
});

In the sample the service worker first looks in the cache, and turns to the network only if it finds nothing.

Cache, local data, and offline operation

The Cache API stores request–response pairs. According to MDN the entries are neither refreshed nor expired by themselves: the script (for example the service worker) must do the refreshing and deletion, typically with versioned cache names. When storage is scarce the browser may delete the data of the origin. IndexedDB, by contrast, handles structured application data (3.6), for example an unfinished note. The two stores serve different purposes:

Store What does it store? Typical offline use
Cache API HTTP responses (HTML, CSS, JavaScript, images) Pages readable offline
IndexedDB Structured application data A note edited offline, an operation queue

Forwarding a modification made offline to the server is a separate synchronization problem: if the student enrolled offline, when the network returns the server must accept or reject the enrolment (full, deadline passed), and the user must be informed about it.

Not the same as an SPA

A service worker can be attached to multi-page and single-page sites alike. The SPA is a model of navigation and interface (6.1); the service worker is one browser tool for requests and background tasks. An SPA does not work offline automatically, and an MPA too can offer pages readable offline.

Worked example: what works offline in Kurzuspont?

Feature Offline? Reason
Reading a course description already opened yes The description and its resources are in the cache.
Number of free places not reliably Live data; the cache may show an old value. The interface says: "last updated: ...".
Writing a note for the course yes, locally Stored in IndexedDB, synchronized when the network returns.
Enrolment no The server must decide; offline only the intention can be recorded, and clear information about this is needed.

This table is at the same time the naming of the offline boundary: the user knows exactly what works and what does not.

Common misconceptions

Statement Clarification
"A service worker paints the interface." It has no direct DOM access; it helps in handling requests and background operations.
"All the data of an offline application is fresh." The local copy reflects the latest known state.
"An SPA works offline by default." A separate storage and request-handling plan is needed.
"The Cache API and IndexedDB are the same." One handles responses, the other structured data.
"The cache refreshes by itself." The application must see to the refreshing.

In brief

  • A service worker is an event-driven component running in the browser that can intercept requests within its scope.
  • It has no DOM access, needs HTTPS (or localhost), and has a separate lifecycle.
  • The Cache API stores responses and does not refresh itself; IndexedDB handles structured data.
  • The limits of offline must be named precisely; synchronizing an offline modification is a separate task.

Review questions

  1. What can a service worker not do that the JavaScript of the page can?
  2. Why is HTTPS needed for a service worker?
  3. What is the difference between the roles of the Cache API and IndexedDB?
  4. Why can an enrolment not be finalized offline?

Learning resources

Prerequisites (2)

  • JavaScript
  • HTTP

Teaches (2)

  • service worker
  • offline web application