Register a service worker
suggest change// Check if service worker is available.
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(function(registration) {
console.log('SW registration succeeded with scope:', registration.scope);
}).catch(function(e) {
console.log('SW registration failed with error:', e);
});
}
- You can call
register()
on every page load. If the SW is already registered, the browser provides you with instance that is already running - The SW file can be any name.
sw.js
is common. - The location of the SW file is important because it defines the SW’s scope. For example, an SW file at
/js/sw.js
can only interceptfetch
requests for files that begin with/js/
. For this reason you usually see the SW file at the top-level directory of the project.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents