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);
});
}
- Call
register()on every page load. If the service worker is already registered, the browser returns the existing registration. - The file can have any name.
sw.jsis common. Registration requires a secure context. - By default, the script’s directory is its scope. A file at
/js/sw.jscan only intercept requests under/js/. Thescopeoption can narrow that, and aService-Worker-Allowedresponse header can widen it. The script is usually placed at the top of the site.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents