-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
94 lines (83 loc) · 2.27 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const version = '1.2'
const appAssets = [
'index.html',
'main.js',
'images/flame.png',
'images/logo.png',
'images/sync.png',
'vendor/bootstrap.min.css',
'vendor/jquery.min.js'
];
const staticCacheName = `static-${version}`
self.addEventListener('install', e => {
e.waitUntil(
caches.open(staticCacheName)
.then(cache => cache.addAll(appAssets))
)
})
self.addEventListener('activate', e => {
let cleaned = caches.keys().then(keys => {
keys.forEach(key => {
if (key !== staticCacheName && key.match('static-')) {
return caches.delete(key)
}
})
})
e.waitUntil(cleaned)
})
//Static cache strategy - Cache with network fallback
const staticCache = (req, cacheName = staticCacheName) => {
return caches.match(req).then(cachedRes => {
if (cachedRes) return cachedRes
return fetch(req).then(networkRes => {
//update cache with new response
caches.open(cacheName)
.then(cache => cache.put(req, networkRes))
return networkRes.clone()
})
})
}
//Network with Cache Fallback
const fallbackCache = async (req) => {
try {
const networkRes = await fetch(req);
//check res is okay, else go to cache
if (!networkRes.ok)
throw 'Fetch Error';
caches.open(staticCacheName)
.then(cache => cache.put(req, networkRes));
//return clone of the network response
return networkRes.clone();
}
catch (err) {
return await caches.match(req);
}
}
// Clean old giphys from the 'giphy' cache
const cleanGiphyCache = giphys => {
caches.open('giphy').then(cache => {
//get all cache entries
cache.keys().then(keys => {
keys.forEach(key => {
if(!giphys.includes(key.url)) cache.delete(key)
})
})
})
}
//sw fetch
self.addEventListener('fetch', e => {
// App Shell
if (e.request.url.match(location.origin)){
e.respondWith(staticCache(e.request))
// Giphy API
} else if (e.request.url.match('https://api.giphy.com/v1/gifs/trending')) {
e.respondWith(fallbackCache(e.request))
//Giphy Media
} else if (e.request.url.match('giphy.com/media')){
e.respondWith(staticCache(e.request, 'giphy'))
}
})
//Listen for message from client
self.addEventListener('message', e => {
if (e.data.action = 'cleanGiphyCache') cleanGiphyCache(e.data.giphys)
})