Created
June 21, 2016 21:22
-
-
Save kosamari/1c2a41243cddecefd79facf877a1a420 to your computer and use it in GitHub Desktop.
cache index.html using Service Worker
This file contains 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
/* | |
* 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]) | |
} | |
})) | |
}) | |
) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Isn't
keyList[i]
on line 42 the same askey
? Why do it like that?