[PWA] 1. Intro to Service Worker

Source: Internet
Author: User

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:

    1. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.