Service worker stays between our browser and noetwork requests. It can help-fetch data from cache and cache the data from the Internet.
To get your service worker, we need to:
- Register the service worker.
Service Worker in We code is just a javascirpt file.
Once the page loaded, we want to register our SERIVCE worker:
Indexcontroller.prototype._registerserviceworker =function () {//Todo:register Service worker if(!navigator.serviceworker)return;//Check Whether service worker is availableNavigator.serviceWorker.register ('/sw.js')//Register the Service worker, locate in. /sw/index.js. Then (reg) ={Console.log ("SW Registered");//Success }) .Catch(ERR) ={Console.log ("SW faild");//wrong })};
in register () function, it can take second param, which are scope, for example:
Navigator.serviceWorker.register ( " / Sw.js " '
So service worker would available only on the '/foo/' scope and its child scope, such as: '/foo/bar ', but not '/foo ', so th E ending '/' is very important. Normally, we don ' t need to add scope, we want our service workers listeren to the root scope, so it's available to all the Child components.
2. Our service worker file:
// Sw.js Self.addeventlistener ('fetch', function (event) { Console.log (event. request);});
Once you fetch the page seond time (first time service work do cache stuff), second time you'll see in the console, the Re is lots of requests log out.
Of course, service worker has other event listeners:
Self.addeventlistener ('Install', Function (Event) { // ..}); Self.addeventlistener ('Activate', Function (Event) { // ..}); Self.addeventlistener ('Fetch', Function (Event) {Console.log (Event. request);});
[Notice] Service worker only works for HTTPS and localhost.
Reference:link
[PWA] 1. Intro to Service Worker