Course contentsShow
← Web Development
Lesson 2311 of 2,98242. Progressive Web AppsFree lesson

Registering a Service Worker

Register a service worker from your main JavaScript and handle registration promises.

Registering a Service Worker

You'll learn how to register a service worker in your main JavaScript and handle the registration lifecycle promises.

Now that you understand what service workers are, their scope, and browser support, it's time to actually register one. Registration is the crucial first step that tells the browser "I have a service worker file—please install and activate it."

The Registration Process

Think of registration like enrolling a new employee at a company. You submit their paperwork (the service worker file), HR processes it (the browser installs it), and eventually they start working (the service worker activates). Registration happens in your main JavaScript file, not in the service worker itself.

You use navigator.serviceWorker.register() and pass it the path to your service worker file. This method returns a Promise, giving you hooks into the success or failure of registration:

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/service-worker.js')
    .then(registration => {
      console.log('Service Worker registered successfully:', registration);
      console.log('Scope:', registration.scope);
    })
    .catch(error => {
      console.error('Service Worker registration failed:', error);
    });
}

Handling Registration Promises

The Promise resolves with a ServiceWorkerRegistration object containing useful information like the scope and references to installing, waiting, and active service workers. The Promise rejects if the file doesn't exist, has syntax errors, or scope issues occur.

You can also use async/await for cleaner syntax:

async function registerServiceWorker() {
  if ('serviceWorker' in navigator) {
    try {
      const registration = await navigator.serviceWorker.register('/service-worker.js');
      console.log('Registered with scope:', registration.scope);
    } catch (error) {
      console.error('Registration failed:', error);
    }
  }
}

Key Takeaway: Service worker registration is initiated from your main JavaScript using navigator.serviceWorker.register(), which returns a Promise you should handle to track success or failure and access the registration object.