DEV Community

Margaret W.N
Margaret W.N

Posted on

Service Worker registration

I learnt how to register a service worker.

Here is how its done:

if('serviceWorker' in navigator){
  window.addEventListener('load', () => {
    navigator.serviceWorker
    .register('sw.js')
    .then(reg => console.log(reg))
    .catch(err => console.log(err))
  })
}
Enter fullscreen mode Exit fullscreen mode

Code explained:

The condition in the if statement checks if the browser supports service workers. Inside the if statement we attach an event listener to listen for the load event. The event fires when the page has loaded then calls a register() function which takes the service worker file as an argument. My service worker is named sw.js. If it successfully registered you log out the response else you log out an error.

The service worker file will contain some code which I'll add once I get it all working.

That's it for Day 66
Let's do this again tomorrow

Oldest comments (0)