Skip to content

ryanburns23/service-worker-register

Repository files navigation

ServiceWorkerRegister

A class expression mixin to register and manage a service worker

Notes

  • Your service-worker.js must be located at the top-level directory relative to your site.
  • It won't be able to control pages unless it's located at the same level or higher than them.
  • Don't register service worker file in, e.g., a scripts/ sub-directory!
  • See w3c/ServiceWorker#468

Usage

Install

bower i ryanburns23/service-worker-register -S

Import the class expression mixin

<link rel="import" href="../bower_components/service-worker-register/service-worker-register.html">

Add ServiceWorkerRegister to your element

class MyElement extends ServiceWorkerRegister(Polymer.Element) {
  static get is() { return 'my-element' }
}

This creates a new class defined by the ServiceWorkerRegister factory, so the inheritance hierarchy is

MyElement <= ServiceWorkerRegister(Polymer.Element) <= Polymer.Element

Listen & Respond to Events

ServiceWorkerRegister distpatches the following events:

  • service-worker-update-available: At this point, the old content will have been purged and the fresh content will have been added to the cache. It's the perfect time to display a "New content is available; please refresh." message in the page's interface.
  • service-worker-content-cached: At this point, everything has been precached. It's the perfect time to display a "Content is cached for offline use." message.

Example:

window.addEventListener('service-worker-update-available', e => this._handleServiceWorkerUpdate(e));
window.addEventListener('service-worker-content-cached', e => this._handleServiceWorkerInstall(e));

_handleServiceWorkerUpdate(){
  // display update message
}
_handleServiceWorkerInstall(){
  // display install message
}

Credits

About

Service worker registration class expression mixin

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages