A class expression mixin to register and manage a service worker
- 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
bower i ryanburns23/service-worker-register -S
<link rel="import" href="../bower_components/service-worker-register/service-worker-register.html">
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
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.
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
}