This example would leave a permission or a service worker on this site, so it opens on its own, in a new tab.

Open in a new tab

A module service worker built on fw's precache serves this page and every file it loads from a versioned cache; the page registers it through swUpdate and lists what its release holds.

Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.

When to use it

A tool, a form or a reader that must open without a network once it has been opened online, and pick up a new release when you publish one.

Copy-paste steps

  1. npm install @awacloud/fw
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ (node serve.js from the examples root does this; any static server works) on localhost or HTTPS: service workers need a secure context.
  3. Copy index.html, main.js and sw.js next to each other and open index.html through that server; then switch the network off and reload. The ../../_style/examples.css link is optional: copy that file along, or delete the link.
  4. List in FILES every file your page loads, and change version on each release. A forgotten file breaks the page offline: keep a check that compares the list with the real import closure of main.js and sw.js.

What it shows

  • sw.js imports fw by its /vendor/fw/ path: a worker does not see the page's import map.
  • precache.factory(cache.factory()).create({ scope: self, prefix, version, urls }).listen(): the release goes into prefix + version at install, older releases of this prefix (never another app's caches) are deleted at activate, and GET requests are served cache-first. The first install takes the page at once, so the second load already works offline.
  • swUpdate.create({ swUrl, onControlled, onUpdateReady }) on the page: registration, the controlled state, and a button that applies a waiting release.
  • cache.keys() / cache.open(name) to list the files of this page's release, once the worker controls the page.

Code

main.js

javascriptApache-2.056 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { swUpdate } from '@awacloud/fw/dom/sw/swUpdate.js';
import { cache } from '@awacloud/fw/dom/sw/cache.js';

fw.runtime.registerAllDeep([swUpdate, cache]);
const UPDATE = fw.runtime.resolve('swUpdate');
const CACHE = fw.runtime.resolve('cache');

/** The cache-name prefix this page owns; `sw.js` adds the release (`v1`). */
export const PREFIX = 'examples-offline-';

/** @param {string} id @param {string} value */
const show = (id, value) => { /** @type {HTMLElement} */ (document.getElementById(id)).textContent = value; };

/**
 * List the files of this page's release in the Cache API, never another
 * app's caches. The Cache API is absent outside secure contexts.
 * @returns {Promise<string[]>} the cached URLs
 */
export async function listCached() {
    if (!('caches' in globalThis)) {
        show('cache-status', 'Cache API not available here');
        return [];
    }
    const name = (await CACHE.keys()).find((/** @type {string} */ key) => key.startsWith(PREFIX));
    const urls = name ? (await (await CACHE.open(name)).keys()).map((/** @type {Request} */ r) => r.url) : [];
    show('cache-status', name ? `${urls.length} files in ${name}` : 'nothing cached yet: the worker is installing');
    /** @type {HTMLElement} */ (document.getElementById('cached')).replaceChildren(...urls.map((url) => {
        const li = document.createElement('li');
        li.textContent = url;
        return li;
    }));
    return urls;
}

/**
 * Register `./sw.js` (scoped to this directory) through `swUpdate`, which
 * also reports a newer release waiting and offers to apply it.
 */
async function start() {
    const updates = await UPDATE.create({
        swUrl: new URL('./sw.js', location.href).pathname,
        // The worker controls the page: the first install claims it, then every reload.
        onControlled: () => { show('sw-status', 'controlling this page: reload it offline'); listCached(); },
        onUpdateReady: () => { show('sw-status', 'a new release is waiting'); apply.hidden = false; },
    });
    if (updates.state === 'unsupported') show('sw-status', 'not supported in this browser: the page works online only');
    else if (updates.state === 'failed') show('sw-status', 'registration failed: the page works online only');
    else if (!updates.controlled()) show('sw-status', 'registered: installing');
    apply.addEventListener('click', () => updates.applyUpdate());
}

const apply = /** @type {HTMLButtonElement} */ (document.getElementById('apply'));
await start();
await listCached();

index.html

htmlApache-2.028 lines

<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>fw · A page that works offline</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>A page that works offline</h1>
    <p>Load this page once online, then switch the network off and reload: the service worker serves the page and every
      file it needs from the cache.</p>
    <dl>
      <dt>Service worker</dt>
        <dd><output id="sw-status"></output> <button id="apply" type="button" hidden>Use the new release</button></dd>
      <dt>Cache</dt><dd><output id="cache-status"></output></dd>
    </dl>
    <ul id="cached" aria-label="Cached URLs"></ul>
  </main>
</body>
</html>

sw.js

javascriptApache-2.023 lines

// SPDX-License-Identifier: Apache-2.0
// A module service worker. A worker does not see the page's import map, so
// it imports fw by the path the map points at: /vendor/fw/ is fw's src/.
import { cache } from '/vendor/fw/dom/sw/cache.js';
import { precache } from '/vendor/fw/dom/sw/precache.js';

/**
 * The page and every file it loads, relative to this worker. The test
 * checks the fw part against the real import closure of main.js and sw.js.
 */
export const FILES = [
    './', './index.html', './main.js', '../../_style/examples.css',
    '/vendor/fw/core/logger.js', '/vendor/fw/core/readyState.js', '/vendor/fw/core/runtime.js',
    '/vendor/fw/core/worker-helper.js', '/vendor/fw/dom/sw/cache.js', '/vendor/fw/dom/sw/precache.js',
    '/vendor/fw/dom/sw/serviceWorker.js', '/vendor/fw/dom/sw/swUpdate.js', '/vendor/fw/io/codec/hex.js',
    '/vendor/fw/main.js',
];

// Versioned cache (prefix + version), old releases deleted on activate, the
// first install takes the page at once, a later one waits for the page.
precache.factory(cache.factory())
    .create({ scope: self, prefix: 'examples-offline-', version: 'v1', urls: FILES })
    .listen();