Skip to content

Instantly share code, notes, and snippets.

@jeffposnick
Last active September 13, 2021 11:53
Show Gist options
  • Save jeffposnick/f3e173a89adfd0ce1e664442ae7f8a27 to your computer and use it in GitHub Desktop.
Save jeffposnick/f3e173a89adfd0ce1e664442ae7f8a27 to your computer and use it in GitHub Desktop.
A modern-ish SW registration script, detecting various state changes.
if ('serviceWorker' in navigator) {
window.addEventListener('load', async function() {
const registration = await navigator.serviceWorker.register('/service-worker.js');
if (registration.waiting && registration.active) {
// The page has been loaded when there's already a waiting and active SW.
// This would happen if skipWaiting isn't being called, and there are
// still old tabs open.
console.log('Please close all tabs to get updates.');
} else {
// updatefound is also fired for the very first install. ¯\_(ツ)_/¯
registration.addEventListener('updatefound', () => {
registration.installing.addEventListener('statechange', (event) => {
if (event.target.state === 'installed') {
if (registration.active) {
// If there's already an active SW, and skipWaiting() is not
// called in the SW, then the user needs to close all their
// tabs before they'll get updates.
console.log('Please close all tabs to get updates.');
} else {
// Otherwise, this newly installed SW will soon become the
// active SW. Rather than explicitly wait for that to happen,
// just show the initial "content is cached" message.
console.log('Content is cached for the first time!');
}
}
});
});
}
});
}
@DervishD
Copy link

May I ask you a question, Jeff?
In other sources I've seen coders testing for registration.installing and if true, doing the statechange handling. Apparently this is for handling SW in the installing state, to wait for them to go into installed state.

As far as I understand, the exact same is achieved by ONLY listen for updatefound event, which when handled guarantees that a SW is in the installing state.

Am I missing anything here and it's mandatory to do BOTH things or is it just a consequence of the spreading of the code of a well-known Udacity course?

Thanks, Jeff!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment