Skip to content

Instantly share code, notes, and snippets.

@kosamari
Created June 21, 2016 21:22
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save kosamari/1c2a41243cddecefd79facf877a1a420 to your computer and use it in GitHub Desktop.
cache index.html using Service Worker
/*
* CHALLANGE:
* Cache `index.html` file using service worker.
*
* This bit of code is included in <script> tag of index.html
* if (navigator.serviceWorker) {
* navigator.serviceWorker.register('serviceworker.js', {scope: '/'})
* }
*
*/
var CACHE_NAME = 'version_01'
var URLS = [ // Add URL you want to cache in this list.
'/', // If you have separate JS/CSS files,
'/index.html' // add path to those files here
]
// Respond with cached resources
self.addEventListener('fetch', function (event) {
event.respondWith(
caches.match(event.request).then(function (request) {
return request || fetch(event.request)
})
)
})
// Cache resources
self.addEventListener('install', function (event) {
event.waitUntil(
caches.open(CACHE_NAME).then(function (cache) {
return cache.addAll(URLS)
})
)
})
// Delete outdated caches
self.addEventListener('activate', function (event) {
event.waitUntil(
caches.keys().then(function (keyList) {
return Promise.all(keyList.map(function (key, i) {
if (key !== CACHE_NAME) {
return caches.delete(keyList[i])
}
}))
})
)
})
@jasoniangreen
Copy link

Isn't keyList[i] on line 42 the same as key? Why do it like that?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment