Skip to content

Instantly share code, notes, and snippets.

@luke-denton-aligent
Last active November 16, 2016 04:01
Show Gist options
  • Save luke-denton-aligent/faac1a69e903fadb56a16fc2240309b7 to your computer and use it in GitHub Desktop.
Save luke-denton-aligent/faac1a69e903fadb56a16fc2240309b7 to your computer and use it in GitHub Desktop.
This snippet shows how to update files that have been cached
// Offline Web Applications course on Udacity https://classroom.udacity.com/courses/ud899
//To trigger a new service worker to be created, the service worker code needs to be updated. This could be as simple
//as adding a comment to the file or, as we're doing here, increasing the cache version from 1 to 2, meaning there
//are likely new elements that need to be cached
var staticCacheName = "my-cache-v2";
//Fires when a service worker becomes active. Means its install has completed and it is now controlling the page
//Cache cleanup has to happen in the activate event because other service workers could still be using an old cache
//whilst the new service worker is spinning up. If the old cache is removed, that old service worker will no longer be
//able to work effectively, and therefore the user will be without any service worker benefits until the new service worker
//is activated and takes over controlling the page
self.addEventListener('activate', function(event) {
event.waitUntil(
//Get all the cache keys
caches.keys().then(function(cacheNames) {
return Promise.all( //Wait for completion of all Promises
//Filter the cache keys to only ones starting with 'my-cache', this will prevent other caches from being found and deleted
cachesNames.filter(function(cacheName) {
return cacheName.startsWith('my-cache') && cacheName != staticCacheName;
}).map(function(cacheName) {
//For each of the found caches that aren't the current cache name and match the required string, delete
return cache.delete(cacheName);
});
);
});
);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment