Angular Service Worker Life Cycle

Register a Service Worker in Angular

How to Register a Service Worker?
To install a service worker you need to kick-start the process by registering it on your page. This tells the browser where your service worker JavaScript file lives.

You can call below register () every time a page loads without concern; the browser will figure out if the service worker is already registered or not and handle it accordingly.

if ('serviceWorker' in navigator) {
  window.addEventListener('load'function() {
    navigator.serviceWorker.register('/sw.js').then(function(registration) {
      // If Registration was successful
      console.log('Success Registration - 'registration.scope);
    },
    function(err) {
      // If Registration was failed!
      console.log('Failed Registration - 'err);
    });
  });
}

This code checks to see if the service worker API is available, and if it is, the service worker at /sw.js is registered once the page is loaded.


Got a minute? Check out this, Angular 6 Questions | A Complete Guide Book
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.