Last active
July 26, 2019 15:55
-
-
Save luke-denton-aligent/e52cff8e13fc4efa0f9d83d7729304d1 to your computer and use it in GitHub Desktop.
This snippet shows how to notify the user of a new version of the site (a new service worker version)
This file contains hidden or 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
// Offline Web Applications course on Udacity https://classroom.udacity.com/courses/ud899 | |
//This code is to be placed in a controller file, not in the service worker itself | |
IndexController.prototype._registerServiceWorker = function() { | |
if (!navigator.serviceWorker) return; //Feature detection | |
var indexController = this; | |
navigator.serviceWorker.register('/sw.js').then(function(reg) { | |
// If there's no controller, this page wasn't loaded via a service worker, so they're looking at the latest version. | |
// In that case, exit early | |
if (!navigator.serviceWorker.controller) return; | |
// If there's an updated worker already waiting, call | |
// indexController._updateReady() | |
if (reg.waiting) { | |
indexController._updateReady(); | |
return; | |
} | |
// If there's an updated worker installing, track its progress. If it becomes "installed", call | |
// indexController._updateReady() | |
if (reg.installing) { | |
indexController._trackInstalling(reg.installing); | |
return; | |
} | |
// TODO: otherwise, listen for new installing workers arriving. | |
// If one arrives, track its progress. | |
// If it becomes "installed", call | |
// indexController._updateReady() | |
reg.addEventListener('updatefound', function() { | |
indexController._trackInstalling(reg.installing); | |
}); | |
}); | |
}; | |
//A function to make it easy to let the user know there is an update ready | |
IndexController.prototype._updateReady = function() { | |
//Toasts view is some external plugin. This is where you will use whatever plugin, message or alert() that you want to notify the user of the update | |
var toast = this._toastsView.show("New version available", { | |
buttons: ['Refresh'] | |
}); | |
}; | |
//A function the track the installation status of a worker | |
IndexController.prototype._trackInstalling = function(worker) { | |
var indexController = this; | |
//The worker will fire a statechange event when moving between 'installing', 'installed', 'active' etc | |
worker.addEventListener('statechange', function() { | |
//If the worker is now installed, let the user know that there is an update ready | |
if (worker.state == 'installed') { | |
indexController._updateReady(); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment