Service Worker Scope

Service worker scope defines which web pages a registered service worker is allowed to control. It limits where fetch events, caching logic, and other service worker features apply within the same origin.

A service worker is registered with a scope that specifies the URL path it can manage. Only pages whose URLs fall within that path can be controlled by the worker after registration and activation.

If no scope is explicitly provided during registration, the browser typically uses the directory containing the service worker script as the default scope. Choosing an appropriate location for the script can therefore affect which pages become eligible for control.

The scope acts as a boundary. Requests and pages outside that boundary are not handled by the service worker, even if they belong to the same website. This helps keep service workers focused on the intended part of an application.

When designing an application, developers should select the smallest scope that satisfies the requirements. A narrower scope reduces the chance of unintentionally affecting unrelated pages while still enabling features such as offline support and request interception where needed.

Key points

Interview questions

How is the default scope determined?

If no scope is specified during registration, the browser generally uses the directory containing the service worker script as the default scope. As a result, the script's location influences which pages can be controlled. Developers can explicitly provide a scope when appropriate, subject to browser rules.

Can a page outside a service worker's scope be controlled by that worker?

No. A page must have a URL that falls within the service worker's registered scope to be controlled by that worker. Pages outside the scope continue operating without that service worker's control unless another applicable service worker exists.

Why would you use a narrow scope instead of the entire site?

A narrow scope keeps the service worker responsible only for the part of the application that needs it. This reduces the chance of unexpected caching or request handling on unrelated pages. It also makes the application's behavior easier to understand and maintain.

What is service worker scope?

Service worker scope is the URL path range where a registered service worker can control pages. Only pages whose URLs fall within that scope are eligible to be controlled. It limits where features such as request interception and caching logic apply. Choosing the correct scope prevents the worker from affecting unrelated parts of a site.