loading...

Service Worker registration

mtee profile image Margaret W.N ・1 min read

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))
  })
}

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

Discussion

pic
Editor guide