Service Worker Basics

  • Service worker runs on a separate single thread .
  • Available for all the pages of the application.
  • Service worker lives on even if browser is closed its a background process 
  • it listen to events and react on events 
  • service worker is attached with scope and tun in background 
Events Listen by Service Worker 
  •  Fetch
  •  Push Notification
  •  Notification Interaction
  •  Background Sync (store user response and send when internet connection is there)
  •  Service Worker life cycle
Service Worker LifeCycle


Steps
  •   Generally Index.html file includes app.js ( general code structure)
  •   From  App.js we can register service worker 
  •   while registering it emits Install event 
  •   After installation is finished Activation event  will be triggered (note that if there is any old         version of service worker is running in some tab than this activation will be not triggered           since as we know service worker is not related to single tab it is associated with scope , and        since  it lives even if tabs are closed so once all tab will be closed it will register new                  version)
  •    after activation service worker control pages which is in the scope
  • After  some time  of idle  Service worker terminate , but it is not uninstalled so it will again respond if there will be any request of its scope come in future .


Register Service Worker 
App.js
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/sw.js')
.then(function() {
console.log('Service worker registered!');
});
}

sw.js
self.addEventListener('install', function(event) {
console.log('[Service Worker] Installing Service Worker ...', event);
});

self.addEventListener('activate', function(event) {
console.log('[Service Worker] Activating Service Worker ...', event);
return self.clients.claim();
});

self.addEventListener('fetch', function(event) {
console.log('[Service Worker] Fetching something ....', event);
event.respondWith(fetch(event.request));
});






Service Worker FAQ
  • Is the Service Worker installed everytime I refresh the page?
       No, whilst the browser does of course (naturally) execute                                      the register()  code everytime you refresh the page, it won't install the          service worker if the service worker file hasn't changed. If it only                          changed     by 1 byte though, it'll install it as a new service worker (but                wait with the activation as explained).
  • Can I unregister a Service Worker?
          Yes, this is possible, the following code does the trick:








Comments

Popular posts from this blog

manifest file

service worker caching