-
Notifications
You must be signed in to change notification settings - Fork 0
/
serviceWorker.js
80 lines (67 loc) · 2.3 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const CACHE = "walleto-v1"
const offlineFallbackPage = [
"/",
"/index.html",
"/css/style.css",
"/css/variables.css",
"/images/offline.png",
"/offline.html",
"https://cdn.jsdelivr.net/npm/@ionic/core/css/ionic.bundle.css",
"https://cdn.jsdelivr.net/npm/@ionic/core/dist/ionic/ionic.esm.js",
"https://cdn.jsdelivr.net/npm/@ionic/core/dist/ionic/ionic.js",
"js/app.js",
"js/icons.js",
"js/main.js",
"js/pages/Home.js",
"js/pages/components/ItemCard.js",
"js/pages/components/DetailedItemModal.js"
];
const self = this;
// Install stage sets up the index page (home page) in the cache and opens a new cache
self.addEventListener("install", function (event) {
console.log("Install Event processing");
event.waitUntil(
caches.open(CACHE).then(function (cache) {
console.log("Cached offline page during install");
if (offlineFallbackPage === "offline.html") {
return cache.add(new Response("Update the value of the offlineFallbackPage constant in the serviceworker."));
}
return cache.addAll(offlineFallbackPage);
})
);
});
// If any fetch fails, it will look for the request in the cache and serve it from there first
self.addEventListener("fetch", function (event) {
if (event.request.method !== "GET") return;
event.respondWith(
fetch(event.request)
.then(function (response) {
console.log("Add page to offline cache: " + response.url);
// If request was success, add or update it in the cache
event.waitUntil(updateCache(event.request, response.clone()));
return response;
})
.catch(function (error) {
console.log("Network request Failed. Serving content from cache: " + error);
return fromCache(event.request);
})
);
});
function fromCache(request) {
// Check to see if you have it in the cache
// Return response
// If not in the cache, then return error page
return caches.open(CACHE).then(function (cache) {
return cache.match(request).then(function (matching) {
if (!matching || matching.status === 404) {
return Promise.reject("no-match");
}
return matching;
});
});
}
function updateCache(request, response) {
return caches.open(CACHE).then(function (cache) {
return cache.put(request, response);
});
}