Service workers by default should reside on the root of the application. To register a service worker st some other location than the default location, you can use the following code.
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw-test/sw.js', {scope: '/sw-test/'})
.then(function(reg) {
// registration worked
console.log('Registration succeeded. Scope is ' + reg.scope);
}).catch(function(error) {
// registration failed
console.log('Registration failed with ' + error);
});
}
From MDN,
- The outer block performs a feature detection test to make sure service workers are supported before trying to register one.
- Next, we use the ServiceWorkerContainer.register() function to register the service worker for this site, which is just a JavaScript
file residing inside our app (note this is the file's URL relative to
the origin, not the JS file that references it.)
- The scope parameter is optional, and can be used to specify the subset of your content that you want the service worker to control. In
this case, we have specified '/sw-test/', which means all content
under the app's origin. If you leave it out, it will default to this
value anyway, but we specified it here for illustration purposes.
- The .then() promise function is used to chain a success case onto our promise structure. When the promise resolves successfully, the
code inside it executes.
- Finally, we chain a .catch() function onto the end that will run if the promise is rejected.
This registers a service worker, which runs in a worker context, and
therefore has no DOM access. You then run code in the service worker
outside of your normal pages to control their loading.