/
sw.js
98 lines (83 loc) · 2.56 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
95
96
97
98
const CACHE_LIST = [
"/",
"/index.html",
"/favicon.svg",
"/logo.svg",
"/trivials.json",
"/js/pequejs.min.js",
"/js/translate.js",
"/js/trivia.js",
"/css/style.css",
"/i18n/en.json",
"/i18n/es.json",
"/trivias/crecienlos80.json",
"/trivias/general_en.json",
"/trivias/nintendo.json",
"/flags/en.svg",
"/flags/es.svg"
];
const STATIC_CACHE_VERSION = `static-v1-23070400000`;
const DEBUG = false;
self.addEventListener('install', function(event) {
if (DEBUG) {
console.log(caches)
console.log("SW Install Event: Is in the process");
}
const onSuccessCachesOpen = (cache) => {
if (DEBUG) {
console.log(cache)
console.log("SW Install Event: Successfully opened the cache and add the cache list");
}
return cache.addAll(CACHE_LIST)
}
// Works like async/await
event.waitUntil(
// caches is a global variable inside the service workers file [readily available]
caches.open(STATIC_CACHE_VERSION).then(onSuccessCachesOpen)
)
})
self.addEventListener('activate', (event) => {
if (DEBUG) console.log("SW Activate Event: Is in the process")
// Google Chrome browseer -> console -> application -> cache -> cache storage
const onSuccessCachesKeys = (cacheNames) => {
// List of cachenames generated by STATIC_CACHE_VERSION
if (DEBUG) console.log(cacheNames)
// Loop through all the keys stored in cache storage
return Promise.all(
cacheNames.map((cache) => {
if (cache !== STATIC_CACHE_VERSION) {
if (DEBUG) console.log(`SW Activate Event: Remove the cache: ${cache}`);
return caches.delete(cache)
}
})
)
}
event.waitUntil(caches.keys().then(onSuccessCachesKeys))
})
self.addEventListener('fetch', (event) => {
const FALLBACK_URL = CACHE_LIST[0];
if (DEBUG) console.log("SW Fetch Event: Is in the process");
const onSuccessFetch = response => {
if (CACHE_LIST.includes(new URL(event.request.url).pathname)) return response
const onSuccessDynamicCacheOpen = cache => {
cache.put(event.request.url, response.clone())
return response
}
return caches
.open(STATIC_CACHE_VERSION)
.then(onSuccessDynamicCacheOpen)
.catch(() => caches.match(FALLBACK_URL))
}
const onErrorFetch = () => {
const onSuccessCacheMatch = response => {
if (response) return response
else return caches.match(FALLBACK_URL)
}
return caches.match(event.request).then(onSuccessCacheMatch)
}
event.respondWith(
fetch(event.request)
.then(onSuccessFetch)
.catch(onErrorFetch)
)
})