My account

PWA and offline

A Progressive Web App is a normal website that can be installed and can work without a network. A manifest gives it a name and an icon, and a service worker sits between the page and the network and decides what comes from the cache. The hard part is not going offline, it is updates - a bad cache rule keeps users on an old version for days. A specialist picks a cache strategy per kind of file, versions the caches, and queues offline writes safely.

Not reviewedWritten with AI helpReading time: 17 minOnline shop exampleService workerJavaScript

Author: bezzad

Contents

The problem: the shop on a train

Many customers of our online shop use it on a phone, on the train, with a weak network. The business asks for three things:

  1. Add the shop to the home screen and open it like an app, without the browser bar.
  2. Open the shop and see the last order list even with no network.
  3. Add products to the cart offline, and send them when the network is back.

A Progressive Web App (PWA) can do all three. It is still one website with one code base. But it adds one new risk: if the cache rules are wrong, users stay on an old version of the shop and you cannot easily fix it.

What makes a site a PWA

  1. HTTPS. Service workers only run on secure pages (localhost is allowed for development).
  2. A web app manifest. A JSON file with the name, icons, colors and start page. The browser uses it to install the app.
  3. A service worker. A script that runs apart from the page and can answer the page’s network requests.
<link rel="manifest" href="/manifest.webmanifest">
{
  "name": "Online Shop",
  "short_name": "Shop",
  "start_url": "/?source=pwa",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#1f4fd1",
  "icons": [
    { "src": "/icon-192.png", "sizes": "192x192", "type": "image/png" },
    { "src": "/icon-512.png", "sizes": "512x512", "type": "image/png" }
  ]
}

The page registers the service worker once:

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js');
}

The place of sw.js matters. A worker at /sw.js can control every page of the site. A worker at /shop/sw.js controls only pages under /shop/.

The service worker lifecycle

sw.js v1sw.js v2v1 controls all open tabsremovedinstallwaiting: old tabs still openactivatev2 controlswithout help, waiting can last for daysskipWaiting(): go to activate nowtime →
A new service worker installs, then waits until no tab uses the old one. Only then it activates and takes control. skipWaiting() skips the wait.

The browser checks sw.js for changes when a page loads. If the file is different, even by one byte, a new version starts:

  1. install: the new worker fills its cache with the files it needs. If one file fails, the install fails and the old worker stays.
  2. waiting: the old worker still controls all open tabs. The new one waits, so one page never mixes old and new code.
  3. activate: when all old tabs are closed, the new worker becomes active. This is the place to delete old caches.
  4. controls: from now on, its fetch handler answers the requests of the pages.

Phones rarely close tabs, so “waiting” can last for days. That is why a good PWA shows “A new version is ready. Reload?” and then calls skipWaiting on purpose.

Cache strategies

strategystep 1step 2good forCache firstread the cachenetwork, if missingapp.3f9a.js, fontsNetwork firstask the networkcache, if offlinepages, order listStale while revalidateanswer from cachenetwork updatesthe cache for next timeproduct images
Pick the strategy for each kind of request. Files that never change can come from the cache. Data that changes must try the network first.

There is no single right strategy. Choose one for each kind of request:

  1. Cache first for files whose name changes when the content changes, like app.3f9a.js. They can never be stale.
  2. Network first for pages and data the user must see fresh, like the order list. The cache is only the offline fallback.
  3. Stale while revalidate for things where a slightly old copy is fine, like product images.
  4. Network only for everything personal or important: payment, sign-in, the cart total. Never answer these from an old cache.
// sw.js: stale while revalidate for product images
self.addEventListener('fetch', (event) => {
  const url = new URL(event.request.url);
  if (!url.pathname.startsWith('/img/products/')) return;

  event.respondWith(caches.open('images').then(async (cache) => {
    const cached = await cache.match(event.request);
    const fresh = fetch(event.request).then((res) => {
      if (res.ok) cache.put(event.request, res.clone());
      return res;
    });
    if (cached) {
      event.waitUntil(fresh.catch(() => {}));
      return cached;
    }
    return fresh;
  }));
});
  1. If the image is in the cache, the user gets it at once. The fetch still runs and updates the cache for next time.
  2. waitUntil keeps the worker alive until the update is done.
  3. A request the handler does not answer (the early return) goes to the network as normal.

Updates without pain

Most PWA bugs are update bugs. Four rules prevent them:

  1. Hashed file names for JS and CSS (your bundler does this). A new build means new names, so cache first is safe.
  2. A version in the cache name, like static-v42, changed by every build. This also changes sw.js, so the browser sees a new worker.
  3. Delete old caches in activate.
  4. Ask the user, then skip waiting.
// sw.js
const STATIC = 'static-v42'; // the build writes the version

self.addEventListener('activate', (event) => {
  event.waitUntil(caches.keys().then((keys) => Promise.all(
    keys.filter((k) => k.startsWith('static-') && k !== STATIC)
      .map((k) => caches.delete(k)),
  )));
});

self.addEventListener('message', (event) => {
  if (event.data === 'skip-waiting') self.skipWaiting();
});
// page: show a banner when a new version is waiting
const reg = await navigator.serviceWorker.register('/sw.js');

function offerUpdate(worker) {
  showBanner('A new version is ready.', 'Reload', () => {
    worker.postMessage('skip-waiting');
  });
}

if (reg.waiting) offerUpdate(reg.waiting);
reg.addEventListener('updatefound', () => {
  const next = reg.installing;
  next.addEventListener('statechange', () => {
    const old = navigator.serviceWorker.controller;
    if (next.state === 'installed' && old) offerUpdate(next);
  });
});

let reloaded = false;
navigator.serviceWorker.addEventListener('controllerchange', () => {
  if (reloaded) return;
  reloaded = true;
  location.reload();
});
  1. The banner shows only when an old worker controls the page. On the first visit there is nothing to update.
  2. After the user clicks, the new worker activates, controllerchange fires, and the page reloads once with the new code.
  3. Calling skipWaiting without asking is possible, but then an open page can run old JS against a new cache. That is fine only for very simple sites.

Writing while offline

Reading offline is easy. Writing offline needs care, because the same action may be sent twice.

  1. Save the action in IndexedDB (localStorage is too small and blocks the page). For example: add product 17, quantity 2.
  2. Show it in the UI as “waiting to send”, so the user is not surprised.
  3. Send the queue when the network is back. The online event works in every browser. Background Sync also works when the tab is closed, but only in Chromium-based browsers, so treat it as a bonus.
  4. Give every action an id (an idempotency key). If the send fails in the middle and runs again, the server sees the same id and does not add the product twice.
  5. Plan for conflicts. The product may be sold out by the time the queue is sent. Tell the user clearly.
async function addToCart(productId, qty) {
  const action = { id: crypto.randomUUID(), productId, qty };
  await queue.add(action);        // IndexedDB, for example with idb
  renderPending(action);
  if (navigator.onLine) await flushQueue();
}

window.addEventListener('online', flushQueue);

Storage limits and privacy

  1. The browser can delete your cache when the disk is low. navigator.storage.persist() asks to keep it, and navigator.storage.estimate() shows how much you use.
  2. Safari can delete data that a script wrote for a site the user has not visited for some days, unless the site is added to the home screen. Never keep the only copy of important data in the browser.
  3. Do not cache personal API answers in a worker cache that outlives sign-out. On sign-out, delete those caches and the IndexedDB queue.
  4. Install and push on iPhone need the user to add the site to the home screen first (push works there since iOS 16.4).

Common mistakes

Mistake Result Better way
Cache first for index.html Users never see a new release. Network first for pages, with an offline page.
The same cache name forever Old files stay, sw.js never changes. Put the build version in the cache name.
Never deleting old caches Storage grows, old files are served. Delete them in activate.
skipWaiting with no reload plan Old page code talks to new files. Ask the user, then reload once on controllerchange.
Caching the cart total or payment answers Wrong prices, private data on shared devices. Network only for personal and money data.
Retrying offline writes with no id Products added twice. An idempotency key on every action.

Summary in 7 lines

  1. A PWA is a normal website plus HTTPS, a manifest and a service worker.
  2. A new worker installs, waits for old tabs, then activates and controls the page.
  3. Choose a cache strategy per kind of request: cache first only for hashed files.
  4. Pages and fresh data use network first; personal and money data use network only.
  5. Put the version in the cache name, delete old caches in activate.
  6. Ask the user before skipWaiting, then reload once on controllerchange.
  7. Queue offline writes in IndexedDB with an id per action, and never keep the only copy of data in the browser.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.