DEV Community

Margaret W.N
Margaret W.N

Posted on

2 1

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

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay