/
service-worker.js
78 lines (41 loc) · 1.62 KB
/
service-worker.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
---
layout: null
---
// This is the "Offline copy of pages" service worker
// Install stage sets up the index page (home page) in the cache and opens a new cache
self.addEventListener("install", function(event) {
var indexPage = new Request("/");
event.waitUntil(
fetch(indexPage).then(function(response) {
return caches.open("spellacy-offline").then(function(cache) {
console.log("{{site.name}} cached index page during install" + response.url);
return cache.put(indexPage, response);
});
}));
});
// If any fetch fails, it will look for the request in the cache and serve it from there first
self.addEventListener("fetch", function(event) {
var updateCache = function(request){
return caches.open("spellacy-offline").then(function (cache) {
return fetch(request).then(function (response) {
console.log("{{site.name}} added page to offline" + response.url)
return cache.put(request, response);
});
});
};
event.waitUntil(updateCache(event.request));
event.respondWith(
fetch(event.request).catch(function(error) {
console.log("{{site.name}} network request failed. Serving content from cache: " + error );
// Check to see if you have it in the cache
//Return response
// If not in the cache, then return error page
return caches.open("spellacy-offline").then(function (cache) {
return cache.match(event.request).then(function (matching) {
var report = !matching || matching.status == 404?Promise.reject("no-match"): matching;
return report
});
});
})
);
})