Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Concept · 25 min · revision 2

Installable and Offline: Service Workers, Manifests and the Limits of PWAs

Register a service worker, watch its lifecycle and update flow end to end, choose a cache strategy per request type, add a web app manifest, and know when a PWA is the wrong tool.

Contentsand lesson path

What you will learn

  • Make an app installable and usable offline with a web app manifest and a service worker (lifecycle, update prompt, cache strategy chosen per request type), and state when a PWA falls short and a native, cross-platform or desktop app is warranted.

Prerequisites: Async JavaScript & Fetch

01. Why it matters

A normal page lives and dies with its network request: no response, no app. A service worker is a script the browser keeps running for your origin, through which every page request can pass. Because it can answer from a cache, the app keeps working on a train, in a basement and during your server's worst hour. Because it persists, the browser can also offer your app as something to install — an icon on the home screen or desktop that opens without browser chrome. Together with a web app manifest, this is what people mean by a Progressive Web App (PWA).

The power comes with a lifecycle you do not control directly. The browser installs, updates and retires service workers on its own schedule, and a careless fetch handler can serve users stale pages forever or, worse, cache another user's private data. This lesson runs a real worker through its whole life — install, activate, an update arriving while a tab is open — and then looks honestly at where PWAs stop being enough.

02. The service worker lifecycle

Registering is one call from a page; everything else happens in the worker file. The worker below precaches its app shell at install, cleans up old caches and claims clients at activate, honours a skip-waiting message, and answers same-origin GETs cache-first:

JavaScript · sw.js — one small worker, four events
const VERSION = 'sw-demo-v1'; // bump this string to ship an update
const SHELL = ['/sw/app.html', '/sw/app.css'];

self.addEventListener('install', (event) => {
  event.waitUntil(caches.open(VERSION).then((c) => c.addAll(SHELL)));
});

self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys()
      .then((keys) => Promise.all(keys.filter((k) => k !== VERSION)
        .map((k) => caches.delete(k))))
      .then(() => self.clients.claim()),
  );
});

self.addEventListener('message', (event) => {
  if (event.data === 'skip-waiting') self.skipWaiting();
});

self.addEventListener('fetch', (event) => {
  const url = new URL(event.request.url);
  const get = event.request.method === 'GET' &&
    url.origin === self.location.origin;
  if (!get) return; // writes and cross-origin requests pass through
  event.respondWith(
    caches.match(event.request).then((hit) => hit ?? fetch(event.request)),
  );
});

The events in order: install (assets are precached — if any fails, the worker never activates), waiting (a worker that installed while an older one still controls open pages), activate (old caches are deleted here, and clients.claim() lets the worker control pages it opened before it existed), and fetch (one handler through which page requests may pass). Note what the fetch handler does not do: it ignores everything except same-origin GETs, so POST requests and cross-origin calls always reach the network untouched.

The page side registers the worker and implements the "update available" prompt:

JavaScript · register, detect the waiting worker, ask the user
const log = (label, value) => console.log(label + ': ' + value);
const reg = await navigator.serviceWorker.register('/sw/sw.js',
  { scope: '/sw/' });
await navigator.serviceWorker.ready;
log('controlled', navigator.serviceWorker.controller ? 'yes' : 'no');

const findWaiting = () => new Promise((resolve) => {
  if (reg.waiting) return resolve(reg.waiting);
  reg.addEventListener('updatefound', () => {
    const installing = reg.installing;
    installing?.addEventListener('statechange', () => {
      if (installing.state === 'installed' &&
          navigator.serviceWorker.controller) resolve(installing);
    });
  });
  setTimeout(() => resolve(null), 6000);
});
const waiting = await findWaiting();
if (waiting) {
  log('new version', 'installed and waiting; the user agrees to update');
  waiting.postMessage('skip-waiting');
} else {
  log('new version', 'none waiting');
  await finish(); // nothing to swap: read the shell as it is
}
navigator.serviceWorker.addEventListener('controllerchange', () => {
  log('controllerchange', 'new deploy took over');
  finish();
});

async function finish() {
  // wait for full activation so old caches are gone before we refetch
  for (let i = 0; i < 20; i += 1) {
    const r = await navigator.serviceWorker.getRegistration('/sw/');
    const done = r?.active?.state === 'activated' &&
      navigator.serviceWorker.controller?.state === 'activated';
    if (done) break;
    await new Promise((resolve) => setTimeout(resolve, 250));
  }
  const css = await fetch('/sw/app.css').then((r) => r.text());
  log('app.css came from', css.split('*/')[0].replace('/* ', '').trim());
}

To reproduce the run below, serve /sw/app.html (any small page) and /sw/app.css, whose first line is the comment /* app shell css, served by deploy 1 */, and paste the page code into the console of /sw/app.html. For the offline part, set DevTools Network to Offline and run fetch('/sw/app.html') and fetch('/storage') from the console. For the new deploy, change the comment to deploy 2 and VERSION to 'sw-demo-v2', reload, and paste the page code again.

Expected output — first visit, then offline, then a new deploy (-- lines are markers; the offline lines sum up the two fetch results)
-- first load (deploy 1) --
controlled: no
new version: none waiting
app.css came from: app shell css, served by deploy 1
-- offline: the shell still loads, an uncached page does not --
cached app shell while offline: GET /sw/app.html -> 200
uncached page while offline: GET /storage -> failed: TypeError
-- a new version ships, the tab reloads --
controlled: yes
new version: installed and waiting; the user agrees to update
controllerchange: new deploy took over
app.css came from: app shell css, served by deploy 2

Three things to notice. On the first visit the page was not yet controlled (controlled: no) — a worker only controls pages from its activation onwards, which is why clients.claim() exists. Offline, the cached shell answered 200 while an uncached path failed outright: the cache boundary is now the app's survival kit, and what you precache decides what survives. And the update arrived while the tab was open: the new worker installed but waited, because swapping workers mid-session would tear the running app out from under the user. Only when the page consented (skip-waiting) did controllerchange fire — the hook that usually triggers one reload into the new version. The browser checks for a new worker script on navigations and bypasses the HTTP cache for that check, so a plain redeploy is all it takes; no clever headers needed on sw.js.

03. Cache strategy is a per-request decision

The demo worker answered everything cache-first, which suits files whose URL changes when their content does (hashed bundles). Most apps need a different policy per kind of request:

Strategies by request type
Request type              Strategy                 Why
Hashed static assets      cache-first              URL changes with content
App shell (HTML)          precache + network       must pick up deploys
API reads that may be     stale-while-revalidate   fast answer, fresh next time
  slightly stale
API reads that must be    network-first            show cached only when offline
  current
Writes, auth, private     network-only             never enters a shared cache
  responses

The last row is a privacy rule, not a performance preference. A service worker cache is keyed by origin and shared by every account that uses that browser. Cache a signed-in user's /api/notes response and the next user of the same browser profile — or any script on the page — can read it from caches.match. Private data belongs in per-account storage (and in the lab, notes live in IndexedDB, partitioned and cleared on sign-out), while the shared cache keeps only the shell and public assets. App shells get their own subtlety: precached HTML is the one thing you usually want served stale-safe, so deployments bump the worker version and the activate step deletes the old cache — the "reload to update" prompt in the lab exists precisely so that swap is the user's decision.

04. Manifest and installability

A web app manifest is a JSON file linked from the page that tells the browser how to present the app as installed:

JSON · manifest.webmanifest
{
  "name": "Offline Notes",
  "short_name": "Notes",
  "description": "Notes that work offline and update live.",
  "start_url": "/",
  "scope": "/",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#0f172a",
  "icons": [
    { "src": "/icon-192.png", "sizes": "192x192", "type": "image/png" },
    { "src": "/icon-512.png", "sizes": "512x512", "type": "image/png" }
  ]
}

start_url is what opens on launch, scope bounds which URLs the installed app may navigate, display: standalone hides the browser UI, and the icons make an install prompt possible. Modern browsers evaluate install criteria before offering installation — served over HTTPS, a valid manifest with name or short_name, start_url, display: standalone (or fullscreen, minimal-ui or window-controls-overlay), both 192 px and 512 px icons, and user engagement heuristics (Chrome dropped the previous fetch-handler requirement in version 108 for mobile and 112 for desktop). Browsers offer install through their own UI, while beforeinstallprompt in Chromium lets the site offer an in-page custom install button. That browser-offered flow is UI, not scriptable from an automated headless run, so treat the install prompt as illustrative here; everything behind it — manifest, worker, cache — has been exercised above. The web.dev Learn PWA course and install criteria guide walk the full requirements per platform.

05. Push, background work and the limits of PWAs

Two adjacent APIs complete the offline picture. Push notifications arrive through a service worker even when no tab is open (the Push API plus the Notification API, gated by a user permission). Background sync defers a task — often "retry my failed POST" — until the browser judges connectivity likely; support varies by browser, so treat it as progressive enhancement, not a dependency. Both are overviews here: they earn their own lessons.

What a PWA still cannot do matters more. It cannot run arbitrary work in the background for minutes at a time, track location continuously on a locked iPhone, use hardware such as Bluetooth on platforms where the API is missing, or ship through an app store's billing rails. When a requirement lands there, the honest alternatives are a native app, a cross-platform framework such as React Native, or a desktop wrapper such as Electron or Tauri — each trading reach for capability. Installable web apps now cover a large share of "app" needs from one codebase, which is why the decision is per requirement, not per project. Rule of thumb: if the app is content, forms and data over HTTPS, a PWA is usually enough; if it needs deep hardware, background execution or store distribution, plan for a native or wrapped build.

06. Check your understanding

Practice check · 3 questions

Lifecycle, strategies and limits

Three situations from the lifecycle above.

Q1. Which of these can a service worker NOT use, even though a page can?
Q2. Your notes app serves GET /api/notes to signed-in users. Where may its response be stored?
Q3. Which manifest field decides what the browser opens when the installed app is launched?
Practice only: not graded, not saved, not evidence.

07. Apply it

For the app in this skill's practice task, write the service worker plan before the code:

  1. List every request type the app makes, and assign each a row from the strategy table.
  2. Decide exactly what the precache list contains, and how a deploy changes VERSION.
  3. Write the update prompt: which event tells the page a worker is waiting, and what the user's yes and no each do.
  4. State which requests must never be intercepted, and how you will test that offline mode cannot expose another account's data.

Then try to break it: reload repeatedly during a deploy, go offline mid-session, and sign out and in as a different user.

08. Review prompt

Without looking back: walk the service worker lifecycle from register to controlling a page, and say where old caches are deleted and why. Why does a new worker wait while old tabs are open, and what three pieces make the "update available" prompt? Match the five request types to their strategies, and explain the privacy rule for shared caches in one sentence. Finally: name two things PWAs cannot do and two situations where you would still choose one.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check