Last active
March 6, 2018 09:56
-
-
Save amitasaurus/31d86eb41e1c2c312c8ab28bf816b24b to your computer and use it in GitHub Desktop.
Handling Service Worker Updates
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
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); | |
} | |
}); | |
} |
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
self.addEventListener('message', function(event) { | |
if (event.data.action === 'skipWaiting') { | |
self.skipWaiting(); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Quick Read : https://redfin.engineering/how-to-fix-the-refresh-button-when-using-service-workers-a8e27af6df68