- Service worker is the new feature from browser which can enable browser to run a script file in the background out side of web page.
- We can check the service worker support by checking the navigator.serviceWorker existence.
- The process for getting a service worker is registering is to browser.We can register a service worker using register() method.
- In this demo, “We will learn to register a basic service worker”.
- Following screenshot shows all the files required for this basic demo.
- The main.js contains the code for registering the service worker service-worker.js .The content of main.js file are as follows:-
if ('serviceWorker' in navigator) { var promiseService = navigator.serviceWorker.register('service-worker.js'); promiseService.then(function(reg) { console.log( "Worker Register successfully.", reg); }).catch(function(err) { console.log( "Worker Register failed.", err); }); }
- The service-worker.js file contains the code definition of service worker.In this file we have 2 event listener for installation and activation.The content of service-worker.js file are as follows:-
self.addEventListener('install', function(event) { console.log('Worker installed successfully', event); }); self.addEventListener('activate', function(event) { console.log('Worker activated successfully', event); });
- The index.html contains the HTML markup and includes the main.js file which start registering the service worker.The content of index.html file are as follows:-
<!DOCTYPE html> <html> <head> <title>Service Worker registration</title> </head> <body> <script src="main.js"></script> </body> </html>
- Following screenshot shows the chrome console of service worker registration:-