Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@DervishD DervishD commented Jan 25, 2021

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