Service Worker Registration and Scope
You'll learn how registering a service worker determines which pages it can control through its scope configuration.
Understanding Service Worker Scope
When you register a service worker, its scope defines the boundaries of its control—essentially which pages and resources it can intercept. Think of scope like a security guard's patrol zone: they only have authority within their assigned area.
The scope is determined by the service worker file's location and can be explicitly set during registration. By default, a service worker controls all pages in its directory and subdirectories.
How Registration Sets the Scope
When you call navigator.serviceWorker.register(), the service worker's URL determines the default scope:
// Service worker at /sw.js controls entire origin
navigator.serviceWorker.register('/sw.js');
// Default scope: '/'
// Service worker in subdirectory
navigator.serviceWorker.register('/app/sw.js');
// Default scope: '/app/'
You can narrow (but not widen) the scope explicitly:
navigator.serviceWorker.register('/sw.js', {
scope: '/products/'
});
// Controls only /products/* pages
Important Scope Rules
- A service worker cannot control pages above its own location (security restriction)
- Place your service worker at the root (
/sw.js) to control your entire site - Multiple service workers can coexist with different scopes
- The most specific scope wins when scopes overlap
Practical Example
// Register at root for site-wide control
navigator.serviceWorker.register('/sw.js')
.then(registration => {
console.log('Scope:', registration.scope);
// Logs: "https://yoursite.com/"
});
Key Takeaway: Service worker scope determines which pages it controls, defaulting to its file location and all paths beneath it—always place your service worker file at the appropriate directory level for your caching strategy.