Last active
September 13, 2021 11:53
-
-
Save jeffposnick/f3e173a89adfd0ce1e664442ae7f8a27 to your computer and use it in GitHub Desktop.
A modern-ish SW registration script, detecting various state changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!'); | |
} | |
} | |
}); | |
}); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
May I ask you a question, Jeff?
In other sources I've seen coders testing for
registration.installing
and if true, doing thestatechange
handling. Apparently this is for handling SW in theinstalling
state, to wait for them to go intoinstalled
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 theinstalling
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!