1001Ferramentas
⚙️ Dev

service-worker.js Generator

Generate a basic service worker with cache-first or network-first strategy and a precache asset list.

service-worker.js:

Offline caching without pulling in Workbox

You want the page to open with no network, but writing a service worker from scratch means getting three events and the lifecycle between them right. Pick a strategy (cache-first or network-first), name a cache version, and list the precache files one per line. The output is a complete service-worker.js with install, an activate that deletes stale caches, and a fetch handler that already skips non-GET requests.

Install uses addAll, which is all or nothing: if a single path in the list returns 404, the whole installation fails and the worker never activates. That is by far the most common reason a service worker refuses to register. Worth knowing too: neither strategy writes new responses into the cache while you browse, only what was in the list. That is what the version field is for, since bumping v1 to v2 makes activate drop the old cache.

Register it with navigator.serviceWorker.register and serve the file from the site root, because scope follows the directory it lives in: at /js/ it only controls /js/. HTTPS is required, with localhost as the exception. The generated code calls skipWaiting and clients.claim, so a new version takes over immediately while the open tab still runs the old JavaScript. Drop those two lines if you prefer the swap on next load.

Frequently asked questions

Cache-first or network-first, which one?
Cache-first for hashed assets whose content never changes. Network-first for HTML and data that change often.
Why does my site not update after a deploy?
Under cache-first the cached file is served indefinitely, because network responses are never written back. Change the cache version value and deploy again.
Does network-first work offline?
Only for files in the precache list. And the fallback triggers when the request actually fails: a 500 from the server is a valid response and goes straight through to the page.

Related Tools