Skip to content

Instantly share code, notes, and snippets.

@v0lkan
Created March 13, 2017 16:38
Show Gist options
  • Save v0lkan/c714a76de48420b264a7db917510f5d9 to your computer and use it in GitHub Desktop.
Save v0lkan/c714a76de48420b264a7db917510f5d9 to your computer and use it in GitHub Desktop.
Invalidates ServiceWorkers so that you can fetch your assets freshly.
/**
* Invalidates the current `ServiceWorker` running on the page.
* Why? Because managing a cache is damn hard; and sometimes due to race conditions
* your assets might get out-of-sync.
*
* This mini snippet checks the version of the app against an uncached resource and
* invalidates the workers if it finds a mismatch.
*/
if ( navigator.serviceWorker && navigator.serviceWorker.getRegistrations ) {
const checkCache = () => {
// `get` uses HTTP fetch API; feel free to replace it with your version of fetching a request.
// version.txt is an “uncached” resource and it only contains the current app version.
//
// Note that certain CDNs can be configured to disregard the query parameters and send
// you a cached copy no matter what you provide in the querystring.
//
// The random querystring parameter `r` is just a preventative measure;
// you should also make sure that `version.txt` is not cached by your CDN, proxy servers etc.
//
// Alternatively, you can do url-rewriting as in `version-some-ramdom-stuff` will give you
// a reliable, uncached version number; that will beat any CDN and proxy caches.
//
// So the choice is up to you; just make absolute sure that the response is fresh and
// **not cached** at all times.
get( `/version.txt?r=${Math.random()}-${(new Date()).getTime()}` )
.then( ( res ) => res.text() )
.then( ( text ) => {
if ( text.trim() !== process.env.VERSION.trim() ) {
console.warn( 'version mismatch! unregistering the current service worker' );
navigator.serviceWorker.getRegistrations().then( ( registrations ) => {
for( let registration of registrations ) {
registration.unregister();
} } );
return;
}
console.log( 'Version match' );
} );
};
checkCache();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment