-
Notifications
You must be signed in to change notification settings - Fork 2
/
sw.js
43 lines (33 loc) · 1.1 KB
/
sw.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
const CACHE_NAME = 'til.mudit.xyz.sw.cache.v1'
async function cacheResources(caches) {
const URLS_TO_CACHE = [
'/',
'/app.js',
'/app.css',
'https://buttons.github.io/buttons.js',
'/red',
'/yellow'
]
const cache = await caches.open(CACHE_NAME)
await cache.addAll(URLS_TO_CACHE)
}
self.addEventListener('install', event => {
event.waitUntil(cacheResources(caches))
})
self.addEventListener('fetch', event => {
event.respondWith(async function () {
const resourceFromCache = await caches.match(event.request)
if (resourceFromCache) {
return resourceFromCache
}
// fetch, cache and return resource
const requestedResource = event.request.clone()
const fetchedResource = await fetch(requestedResource);
if (fetchedResource && fetchedResource.status === 200 && (fetchedResource.type === 'basic' || fetchedResource.type === 'cors')) {
const fetchedResourceForCache = fetchedResource.clone()
const cache = await caches.open(CACHE_NAME)
await cache.put(event.request, fetchedResourceForCache)
}
return fetchedResource
}())
})