Service Worker with automatic cache management for your PWA.
- Install from
npm
or clone fromgithub
. - Copy
sw.js
to root directory of web app. - Edit
sw.js
, renamingname
& settingurls
to the required files to run web app offline. - Increment the
version
integer any time a core asset changes to delete a stale cache. - Install
sw.js
in web app (seeloader.js
).
(function () {
function log (arg) {
console.type(`[my-app:${new Date().getTime()}] ${arg}`);
}
if ("serviceWorker" in navigator) {
window.addEventListener("load", async () => {
try {
const registration = await navigator.serviceWorker.register("/sw.js", {scope: "/"});
log(`type=serviceWorker, message="ServiceWorker registration successful with scope: ${registration.scope}"`);
} catch (err) {
log(`type=error, source=serviceWorker, message="ServiceWorker registration failed: ${err.message}"`);
}
});
}
}());
Install with npm
& use the cli to generate a service worker in the current directory.
$ npm i tiny-serviceworker -g
$ sw --name="myapp" --directories="assets/css,assets/js,assets/img" --loader=true
Name of your PWA
Boolean to enable a client.postMessage("version_$version");
Quoted comma delimited relative (from root) directory names to include in generated service worker
Quoted comma delimited relative (from root) files to include in generated service worker
Boolean to auto-increment version
integer in sw.js
Quoted comma delimited relative (from root) directories or files to exclude; supports * for wildcards
Quoted comma delimited hostnames valid for caching requests
Boolean to generate loader.js
script for sw.js
Boolean to force clients to reload when cache has gone stale
Boolean to load service worker in Safari browser (based on navigator.userAgent
)
Default cache TTL (seconds) on requested URLs. Does not apply to core assets!
Cache version. Increment when core assets change.
Boolean to enable/disable walking directories for cache inclusion