-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw.js
79 lines (64 loc) · 2.04 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
const staticCache = 'site-static-v2';
const pokemonCache = 'pokemon-dynamic-v2';
// here we need to store request urls !
const assets = [
'/',
'/index.html',
'/js/main.js',
'/data/poke_desc.json',
'/css/style.css',
'/manifest.json',
'img/dresseur_16x16.ico',
'img/loader.gif',
'img/icons/pokedex_80x80.png',
'img/icons/pokedex_512x512.png',
'img/icons/maskable_icon.png',
'img/icons/speaker_icon.png',
];
// if SW is installed
self.addEventListener('install', evt => {
// need to be sure caching is done before the install event stop !
evt.waitUntil(
caches.open(staticCache).then(cache => {
// getAllPokemon(); // after we cached static file --> cache pokemon info
console.log("Caching static assets !");
return cache.addAll(assets);
})
);
});
// fetch event --> if a file was cached and we're offline --> return this page
// the pokemon cache will be created after every pokemon are loaded
self.addEventListener('fetch', evt => {
evt.respondWith(
caches.match(evt.request).then((cacheRes) => {
// if cachesRes is empty --> redo the fetch request and store in dynamic cache
return cacheRes || fetch(evt.request)
.then(fetchRes => {
return caches.open(pokemonCache).then(cache => {
cache.put(evt.request.url, fetchRes.clone());
return fetchRes;
})
});
})
)
});
// activate service worker
// self.addEventListener('activate', evt => {
// evt.waitUntil(
// caches.keys().then((keys => {
// console.log(keys); // get all versions of caches
// return Promise.all(keys
// .filter(key => key != staticCache)
// .map(key => caches.delete(key)) // delete all but not the cache names atline first
// )
// }))
// )
// })
// we want to cache all pokemon informations once and be able to retrieve those offline
// self.addEventListener("fetch", event => {
// if (event.request.url.includes("/api/")) {
// console.log("yeah yeah"); // test
// } else {
// console.log("euh...");
// }
// });