Skip to content

Instantly share code, notes, and snippets.

@bennypowers
Created November 27, 2017 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennypowers/5ecbb06a284160544f34867142885ebf to your computer and use it in GitHub Desktop.
Save bennypowers/5ecbb06a284160544f34867142885ebf to your computer and use it in GitHub Desktop.
async _registerServiceWorker() {
// Instructions on how to toast the user when necessary. 🍾
const toast = () => this.$.swtoast.open();
// Listen for changes on a new worker, toast when installed. 🍞
const track = (sw) => sw.onstatechange = () => (sw.state === 'installed') && toast();
// Register the service worker
const scope = Polymer.rootPath;
let reg;
try {
reg = await navigator.serviceWorker.register('/service-worker.js', {scope});
} catch (e) {
// eslint-disable-next-line no-console
return console.info('Could not register service worker.', e);
}
// If there's no previous SW, quit early - this page load is fresh. 🍌
if (!navigator.serviceWorker.controller) return;
// A new SW is already waiting to activate. Toast the user to update. 👯
// Or, if user has not yet interacted with the page, reload.
else if (reg.waiting) return this._hasInteracted
? toast()
: location.reload();
// A new SW is installing. Listen for updates, toast when installed. 🍻
else if (reg.installing) track(reg.installing);
// Otherwise, when a new service worker arrives, listen for updates,
// and if it becomes installed, toast the user. 🍷
else reg.onupdatefound = () => track(reg.installing);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment