Skip to content

Instantly share code, notes, and snippets.

@matthewhartman
Created March 6, 2020 08:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewhartman/affb854ba3c2941bab6c87b66f29422d to your computer and use it in GitHub Desktop.
Save matthewhartman/affb854ba3c2941bab6c87b66f29422d to your computer and use it in GitHub Desktop.
Service Worker Code
// Service Worker
var CACHE_NAME = 'v-1'
// Initial Assets to Cache
var urlsToCache = [
'/',
'/index.html',
'/android-chrome-144x144.png',
'/android-chrome-192x192.png',
'/android-chrome-512x512.png',
'/apple-touch-icon.png',
'/browserconfig.xml',
'/favicon.ico',
'/favicon-16x16.png',
'/favicon-32x32.png',
'/mstile-150x150.png',
'/site.webmanifest'
]
// Install the service worker and skip waiting
// Skip waiting is essential to work correctly with iOS devices
self.addEventListener('install', function(event) {
self.skipWaiting();
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache', CACHE_NAME)
return cache.addAll(urlsToCache)
})
)
})
// For every new asset that is fetched, add it to the cache list
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
if (response) {
console.log('Found ', event.request.url, ' in cache')
return response
}
return fetch(event.request).then(function(response) {
if(!response || response.status !== 200 || response.type !== 'basic') {
return response
}
var responseToCache = response.clone()
caches.open(CACHE_NAME)
.then(function(cache) {
cache.put(event.request, responseToCache)
})
return response
})
})
)
})
// If a new cache name is present, delete the old cache and create a new one
self.addEventListener('activate', (event) => {
var cacheKeeplist = [CACHE_NAME]
event.waitUntil(
caches.keys().then((keyList) => {
return Promise.all(keyList.map((key) => {
if (cacheKeeplist.indexOf(key) === -1) {
return caches.delete(key)
}
}))
})
)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment