forked from firtman/cds21
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserviceworker.js
60 lines (53 loc) · 1.7 KB
/
serviceworker.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
const assetsName = "PWA_ASSETS"
const urls = [
"/",
"/js/app.js",
"/js/handlers.js",
"/data/activities.json",
"/styles.css"
]
// Install, or precache, the assets
self.addEventListener('install', event => {
event.waitUntil(
caches.open(assetsName)
.then(cache => {
cache.addAll(urls)
})
)
})
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => {
// Even if response exists in cache, it is fetched and updates the cache for the
let fetchPromise = fetch(event.request)
.then(networkResponse => {
caches.open(assetsName).then(cache => {
cache.put(event.request, networkResponse.clone())
return networkResponse
})
})
return response || fetchPromise
})
)
})
// Create a custom HTTP response with 'fetch' event
// self.addEventListener('fetch', event => {
// const response = new Response(`service worker responding for ${event.request.url}`);
// event.respondWith(response); // HTTP response, or a promise of an HTTP response
// })
// Cache First
// self.addEventListener('fetch', event => {
// event.respondWith(
// caches.match(event.request) // searching the cache
// .then(res => {
// if(res) return res // CACHE HIT
// return fetch(event.request) // CACHE MISS! Return a network fetch, instead.
// })
// )
// })
// Synthesizing responses (troubleshooting)
// self.addEventListener("fetch", event => {
// const response = new Response(`service worker responding for ${event.request.url}`);
// event.respondWith(response); // HTTP response, or a promise of an HTTP response
// });