JavaScript Workers Register a service worker

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9

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.


Got any JavaScript Question?