Service Worker Registration from HTML
Register a service worker with a script tag and navigator API.
Service Worker Registration from HTML is a free HTML Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the HTML Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What a Service Worker Is
A service worker is a JavaScript file that runs in the background, separate from any page, intercepting network requests for its scope. It powers offline support, push notifications, background sync, and faster repeat loads via caching.
Registration
Register the worker from a page script: navigator.serviceWorker.register("/sw.js"). The browser fetches /sw.js, parses it, runs its install event, and starts intercepting requests for the registration's scope.
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/sw.js")
.then((reg) => console.log("Registered, scope:", reg.scope))
.catch((err) => console.error("Registration failed:", err));
}Feature Detect First
Old browsers do not support service workers. Always feature-detect with "serviceWorker" in navigator before calling register, otherwise the call throws on browsers that lack the API. Polyfilling is not viable — service workers cannot be polyfilled because they require browser-level integration.
Scope
The scope is the path prefix the worker controls. By default, scope is the directory of the worker file: /sw.js controls all URLs under /. To register a deeper-scoped worker from a different file location, set the scope option AND serve the Service-Worker-Allowed header.
Where to Place sw.js
Place sw.js at the application root (/sw.js) so its default scope covers the entire site. Deeper paths (/app/sw.js) limit scope to /app/ and below, which is rarely what you want.
Registration Timing
Register the worker after the page has loaded to avoid competing for bandwidth during critical render: window.addEventListener("load", () => navigator.serviceWorker.register("/sw.js")). The PWA features kick in on subsequent visits without delaying the first visit.
Updates
The browser checks for an updated sw.js automatically (typically every 24 hours, and on most page loads). If the file content has changed, the new worker is downloaded, installs, and waits in "waiting" state until all existing tabs close — then it activates.
Forcing Updates
registration.update() manually triggers an update check. self.skipWaiting() inside the new sw.js activates immediately without waiting for tabs to close. Combine for "always run the latest worker" behavior, at the cost of mid-session re-fetching.
Unregistering
registration.unregister() removes the worker. Useful during development if a buggy worker is breaking your site. In Chrome DevTools, Application → Service Workers offers a "Unregister" button for the same purpose during debugging.
Common Mistake
Registering a worker over HTTP (without HTTPS) silently fails — service workers require a secure origin (HTTPS, or localhost for development). Check the console for the "An SSL certificate error occurred" message if registration is not taking effect.
Coordinating Worker and Page
The worker has no DOM access. To pass messages, use navigator.serviceWorker.controller.postMessage() from the page and self.addEventListener("message", handler) in the worker (and vice versa). Useful for cache invalidation, version checks, custom events.
First-Visit vs Repeat-Visit
On the first visit, the worker installs and starts controlling pages only after the page is reloaded. To control the first navigation immediately, call self.clients.claim() in the activate event — useful for offline-first apps.
Knowledge Check
Why must service workers be served over HTTPS (or localhost)?
Summary
Register service workers from page JS with navigator.serviceWorker.register("/sw.js") after feature detection. Place sw.js at the application root for full scope. Register on load to avoid competing with critical render. Updates auto-check periodically; force with registration.update or skipWaiting. Requires HTTPS to prevent malicious worker injection.
Frequently asked questions
Is the “Service Worker Registration from HTML” lesson free?
Yes — the full text of “Service Worker Registration from HTML” is free to read here on the web, and the HTML Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the HTML Academy course, upgrade to CoddyKit PRO.
What will I learn in “Service Worker Registration from HTML”?
Register a service worker with a script tag and navigator API. You practise HTML Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start HTML Academy?
No prior experience is required. HTML Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Service Worker Registration from HTML” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this HTML Academy lesson?
Yes. Every HTML Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- The Web App Manifest
- Service Worker Registration from HTML
- Theme Color and App Icons
- Offline Fallback Page