Skip to content
Tutorials Center
My learning

Topics

Lesson 99 of 122 ยท Web APIs

Progressive Web Apps: Manifest and Service Workers

Turn a website into an installable app. Write a web app manifest, register a service worker, cache files for offline use and pick a caching strategy.

A Progressive Web App (PWA) is an ordinary website that behaves a little like an installed app. Visitors can add it to their home screen or desktop, open it in its own window without browser toolbars, and keep using parts of it when the network is slow or gone. There is no special file format and no app store: a PWA is HTML, CSS and JavaScript plus two extra ingredients.

  1. A web app manifest, a small JSON file that tells the browser the app's name, icons and colors.
  2. A service worker, a script that sits between your page and the network and can answer requests from a cache.

This lesson covers the basics of both. You should be comfortable with Web Workers, because a service worker is a special kind of worker, and with the security rules from Introduction to Web APIs.

What makes an app "progressive"

The word progressive means the site works for everyone and gets better where the browser can do more. A browser without service worker support still shows the normal website. One with support adds offline caching and installation. Nothing breaks for anyone.

PWAs need a secure context: the site must be served over HTTPS (or from localhost while you develop). Service workers can intercept every request, so browsers refuse to run them on pages that an attacker could tamper with.

The web app manifest

The manifest is a JSON file, usually named manifest.webmanifest (some sites use manifest.json). You connect it to each page with a <link> in the <head>:

HTML
<link rel="manifest" href="/manifest.webmanifest">
<meta name="theme-color" content="#0b5fff">

The server should send the file with the media type application/manifest+json. A small but realistic manifest looks like this:

JSON
{
  "id": "/",
  "name": "Pocket Recipes",
  "short_name": "Recipes",
  "description": "Save and cook your favorite recipes.",
  "start_url": "/?source=pwa",
  "scope": "/",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#0b5fff",
  "icons": [
    { "src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png" },
    { "src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png" },
    {
      "src": "/icons/maskable-512.png",
      "sizes": "512x512",
      "type": "image/png",
      "purpose": "maskable"
    }
  ]
}

The most important members are:

Member Purpose
name Full name, shown on install prompts and splash screens.
short_name A short label for places with little room, such as under a home-screen icon.
start_url The page that opens when the app is launched. Add a query such as ?source=pwa to tell launches from normal visits in your analytics.
scope Which URLs belong to the app. Links outside the scope open in a normal browser tab.
display How the app is framed: browser (a normal tab), minimal-ui, standalone (its own window, no address bar) or fullscreen.
background_color Color shown while the app starts.
theme_color Color of the window's title bar or toolbar. The <meta name="theme-color"> tag sets the same for the browser.
icons A list of images with src, sizes and type. Provide at least a 192 by 192 and a 512 by 512 PNG.
id A stable identity for the app, so changing start_url later does not create a "new" app.

A purpose of maskable marks an icon that has extra safe space around the logo, so the operating system can crop it into a circle, squircle or other shape without cutting off the picture. Many sites provide both a regular and a maskable icon. For ordinary browser-tab icons see Favicons.

The manifest only supplies data. The browser reads it and decides what to offer.

What installability needs

Rules differ between browsers and change over time, so treat this list as a guide and test in your target browsers. Chromium-based browsers (Chrome, Edge) generally want:

  • the page served over HTTPS,
  • a manifest with name (or short_name), icons including 192 and 512 pixel sizes, start_url, and a display of standalone, fullscreen or minimal-ui,
  • the manifest linked from the page.

When these hold, the browser may show an install button in the address bar or menu. Safari lets people choose Add to Home Screen or Add to Dock from its share menu and also reads your manifest. Firefox on Android supports installing too; Firefox on desktop does not install web apps.

You can detect whether the app is currently running as an installed app with a media query, which lets you hide an "Install" hint that makes no sense there:

JavaScript
const installed = window.matchMedia('(display-mode: standalone)').matches;

The next example checks a manifest the way a build tool or audit might. It parses a JSON string and reports which of the common requirements are met. Edit the JSON, for example delete the 512 icon, and run it again.

Checking a manifest

The last check fails on purpose: a maskable icon is optional, but it is the polish that stops your logo from looking squeezed on some phones.

Service workers

A service worker is a JavaScript file that the browser runs in the background, separate from any page, much like the workers in Web Workers. It has no access to the DOM. Instead, it can listen for the fetch event, which fires whenever a page under its scope requests anything: HTML, CSS, images, API calls. The service worker can then answer from a cache, ask the network, or mix both.

You register it from your page:

HTML
<script>
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
      navigator.serviceWorker.register('/sw.js')
        .then((registration) => console.log('Scope:', registration.scope))
        .catch((error) => console.error('Registration failed:', error));
    });
  }
</script>

Two details matter here. The feature check keeps the page working in browsers without support. And the scope of a worker defaults to the folder that contains the script, so /sw.js controls the whole site, while /blog/sw.js would control only /blog/. Put the file at the root unless you have a reason not to.

The lifecycle

A service worker moves through clearly defined stages, which exist so that an old and a new version never fight over the same pages.

stateDiagram-v2
    [*] --> Installing: register()
    Installing --> Installed: install event done
    Installed --> Activating: no older worker in use
    Activating --> Activated: activate event done
    Activated --> Redundant: replaced by a newer worker
    Installing --> Redundant: install failed
    Redundant --> [*]

A service worker is installed, waits until the old version is no longer used, then activates.

  • install fires once per version. This is where you download and cache the files your app needs to start.
  • activate fires when the worker takes control. This is where you delete caches that belong to old versions.
  • A new version waits until every tab using the old one is closed, unless you call self.skipWaiting().
  • A newly activated worker controls only pages loaded after it, unless it calls clients.claim().

A minimal offline-ready worker

Here is a complete sw.js that stores a few core files when installed and serves them from the cache. It is read-only because service workers cannot run inside the sandboxed examples on this site.

JavaScript
const CACHE = 'pocket-recipes-v1';
const CORE_FILES = ['/', '/styles.css', '/app.js', '/offline.html'];

self.addEventListener('install', (event) => {
  event.waitUntil(caches.open(CACHE).then((cache) => cache.addAll(CORE_FILES)));
});

self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((names) =>
      Promise.all(names.filter((n) => n !== CACHE).map((n) => caches.delete(n)))
    )
  );
});

self.addEventListener('fetch', (event) => {
  if (event.request.method !== 'GET') return;

  event.respondWith(
    caches.match(event.request).then(
      (cached) => cached || fetch(event.request).catch(() => caches.match('/offline.html'))
    )
  );
});

Notice event.waitUntil() and event.respondWith(). A service worker can be stopped by the browser at any moment, so these calls tell it "stay alive until this promise finishes". The caches object is the Cache Storage API: named caches that map requests to responses. When you ship new files, change the cache name (v2) so the activate step cleans out the old ones.

Caching strategies

How should the fetch handler decide between the cache and the network? There is no single best answer, so PWAs combine a few well-known patterns:

Strategy How it works Good for
Cache first Answer from the cache; go to the network only on a miss. Fonts, icons, versioned CSS and JS files that never change.
Network first Try the network; fall back to the cache when offline. Pages and data where fresh content matters, such as news.
Stale while revalidate Answer from the cache immediately, and update the cache from the network in the background. Avatars, feeds and anything where "a bit old" is fine.
Network only Never cache. Payments, logins, analytics beacons.

Because service workers cannot run here, the example below simulates the first two strategies with a plain Map as the cache and a fake network that can be switched off. The logic is the same as in a real worker.

Cache first versus network first

Read the output from the top: cache first goes to the network once and then never again, while network first keeps asking the network and uses the cache only when it fails. Visiting a page that was never cached while offline needs a fallback, which is why the real worker above also stores /offline.html.

Practical advice

  • Start small. A manifest alone already makes a site installable in many browsers. Add offline support for a few core pages before trying to cache everything.
  • Version your caches. Forgetting to change the name is the most common reason users keep seeing old files.
  • Never cache what is private. Pages that show account data should not end up in a shared cache.
  • Update with care. A service worker file itself is checked by the browser for changes on each visit; avoid caching sw.js for a long time on the server.
  • Test with DevTools. The Application panel (Chrome and Edge) or Storage (Firefox) shows manifests, workers and caches, and lets you simulate offline mode. See Viewing Source and Using DevTools.
  • Think about size. Caching big media files can fill a visitor's storage. Pair it with the ideas in Fast-Loading HTML.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the web app manifest?

    The manifest is a JSON file linked with <link rel="manifest">. It gives the browser the information needed to install the site as an app.
  2. 2. A service worker is registered from /blog/sw.js. Which pages can it control by default?

    By default a worker's scope is the folder that contains the script, so /blog/sw.js controls URLs under /blog/.
  3. 3. Which caching strategy suits a news article where fresh content matters but offline reading is still nice to have?

    Network first returns the newest article when the network works, and uses the cached copy only when the request fails.
  4. 4. Why does the example worker delete caches whose name differs from the current one in the activate event?

    Each release uses a new cache name. Cleaning old caches in activate frees storage and prevents users from seeing outdated files.
  5. 5. Where can a service worker run?

    A service worker can intercept every request, so browsers require a secure context to run it.

Summary

  • A PWA is a normal website plus a manifest (installation data) and a service worker (offline and caching logic).
  • Link the manifest with <link rel="manifest">; give it name, start_url, display, colors and at least 192 and 512 pixel icons, ideally with a maskable one.
  • Service workers need HTTPS or localhost, run in the background without DOM access, and listen to install, activate and fetch.
  • Use caches.open(), cache.addAll() and caches.match() for the Cache Storage API, and version your cache names.
  • Choose a strategy per resource: cache first, network first, stale while revalidate or network only.

Next lesson: Web Share, Clipboard and Notifications APIs, which let your page hand content to other apps, copy text and talk to the user outside the page.