JavaScript Register a service worker


Example

// 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 intercept fetch requests for files that begin with /js/. For this reason you usually see the SW file at the top-level directory of the project.