Skip to content

Instantly share code, notes, and snippets.

@amitasaurus
Last active March 6, 2018 09:56
Show Gist options
  • Save amitasaurus/31d86eb41e1c2c312c8ab28bf816b24b to your computer and use it in GitHub Desktop.
Save amitasaurus/31d86eb41e1c2c312c8ab28bf816b24b to your computer and use it in GitHub Desktop.
Handling Service Worker Updates
navigator.serviceWorker.register('/sw.js').then(function(reg) {
//page has loaded from the network and not sw
if (!navigator.serviceWorker.controller) {
return;
}
//if sw is in waiting state
if (reg.waiting) {
//call the update function
updateReady(reg.waiting);
return;
}
//if sw is in installing state
if (reg.installing) {
trackInstalling(reg.installing);
return;
}
//if update is found
reg.addEventListener('updatefound', function() {
trackInstalling(reg.installing);
});
// Ensure refresh is only called once.
// This works around a bug in "force update on reload".
//if new SW is loaded this event will fire and reload the page
var refreshing;
navigator.serviceWorker.addEventListener('controllerchange', function() {
if (refreshing) return;
window.location.reload();
refreshing = true;
});
}
//update message
function updateReady(worker) {
//do something , show a dialog to update
//on "update" send a message to sw
worker.postMessage({
action: 'skipWaiting'
});
}
//Observe SW in installing stage
function trackInstalling(worker) {
//listening to state change
worker.addEventListener('statechange', function() {
//if state is 'installed' show update message
if (worker.state == 'installed') {
updateReady(worker);
}
});
}
self.addEventListener('message', function(event) {
if (event.data.action === 'skipWaiting') {
self.skipWaiting();
}
});
@amitasaurus
Copy link
Author

amitasaurus commented Mar 6, 2018

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