-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
sw.js
82 lines (77 loc) · 2.21 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
//GET VERSION
const CACHE_VERSION = "0.1.9";
const CURRENT_CACHE = `sbio-v${CACHE_VERSION}`;
let filesToCache = [
"./manifest.json",
"https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght@400;500&display=swap",
"https://fonts.gstatic.com/s/sourcecodepro/v23/HI_SiYsKILxRpg3hIP6sJ7fM7PqlPevWnsUnxg.woff2",
"./css/style.css",
"./img/ico.ico",
"./img/ico.png",
"https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js",
"https://cdnjs.cloudflare.com/ajax/libs/cannon.js/0.6.2/cannon.min.js",
"https://cdn.jsdelivr.net/npm/party-js@latest/bundle/party.min.js",
"./js/script.min.js",
`./sw.js?v=${CACHE_VERSION}`,
"./js/pwa/pwa.min.js",
"./js/lib/png2share.min.js",
"./index.html",
"./",
];
//INSTALL
self.addEventListener("install", eo => {
console.log("Installing service worker");
eo.waitUntil(
caches.open(CURRENT_CACHE)
.then(cache => {
console.log("Caching...")
cache.addAll(filesToCache);
})
);
});
// on activation we clean up the previously registered service workers
self.addEventListener('activate', evt => {
console.log("Activating service worker");
evt.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheName !== CURRENT_CACHE) {
console.log("Deleting old cache");
return caches.delete(cacheName);
}
})
)
})
);
});
const updateRequest = (request, response) => {
if (!request.url.includes(".woff")) {
caches.open(CURRENT_CACHE)
.then(cache => {
cache.match(request)
.then(res => {
if (res) {
cache.put(request, response);
}
})
})
}
}
self.addEventListener('fetch', event => {
event.respondWith(
(async () => {
if(navigator.onLine) {
// Fetch the resource from the network. And update cache.
const response = await fetch(event.request);
if (response) {
updateRequest(event.request, response.clone());
}
return response;
}
// Otherwise return cache if error found or item not found
// Ask for refresh the page
return await caches.match(event.request);
})()
);
});