A page that works offline
Make a page work offline with a module service worker and a versioned precache.
Apache-2.0Opens in a new tab
Package: @awacloud/fw
This example would leave a permission or a service worker on this site, so it opens on its own, 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
npm install @awacloud/fw- Serve
node_modules/@awacloud/fw/src/at/vendor/fw/(node serve.jsfrom the examples root does this; any static server works) onlocalhostor HTTPS: service workers need a secure context. - Copy
index.html,main.jsandsw.jsnext to each other and openindex.htmlthrough that server; then switch the network off and reload. The../../_style/examples.csslink is optional: copy that file along, or delete the link. - List in
FILESevery file your page loads, and changeversionon each release. A forgotten file breaks the page offline: keep a check that compares the list with the real import closure ofmain.jsandsw.js.
What it shows
sw.jsimports 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 intoprefix + versionat 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
// 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
<!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
// 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();