Repository navigation
Expand file tree
/
Copy pathworker.js
More file actions
109 lines (87 loc) · 2.88 KB
/
Copy pathworker.js
File metadata and controls
109 lines (87 loc) · 2.88 KB
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
99
100
101
102
103
104
105
106
107
108
109
(function () {
"use strict";
/* global importScripts */
/* global self */
/* global caches */
/* global fetch */
/* global URL */
// Include SW cache polyfill
importScripts("/r3search/js/serviceworker-cache-polyfill.js");
// Cache name definitions
var cacheNameStatic = "r3search-static-v4";
var cacheNameWikipedia = "r3search-wikipedia-v1";
var cacheNameTypekit = "r3search-typekit-v1";
var currentCacheNames = [
cacheNameStatic,
cacheNameWikipedia,
cacheNameTypekit
];
// A new ServiceWorker has been registered
self.addEventListener("install", function (event) {
event.waitUntil(
caches.open(cacheNameStatic)
.then(function (cache) {
return cache.addAll([
"/r3search/",
"/r3search/js/app.js",
"/r3search/css/app.css",
"/r3search/img/loading.svg"
]);
})
);
});
// A new ServiceWorker is now active
self.addEventListener("activate", function (event) {
event.waitUntil(
caches.keys()
.then(function (cacheNames) {
return Promise.all(
cacheNames.map(function (cacheName) {
if (currentCacheNames.indexOf(cacheName) === -1) {
// TODO: if wikipedia cache changed, remove localStorage history
return caches.delete(cacheName);
}
})
);
})
);
});
// The page has made a request
self.addEventListener("fetch", function (event) {
var requestURL = new URL(event.request.url);
event.respondWith(
caches.match(event.request)
.then(function (response) {
if (response) {
return response;
}
var fetchRequest = event.request.clone();
return fetch(fetchRequest).then(
function (response) {
var shouldCache = false;
if (response.type === "basic" && response.status === 200) {
shouldCache = cacheNameStatic;
} else if (response.type === "opaque") { // if response isn"t from our origin / doesn"t support CORS
if (requestURL.hostname.indexOf(".wikipedia.org") > -1) {
shouldCache = cacheNameWikipedia;
} else if (requestURL.hostname.indexOf(".typekit.net") > -1) {
shouldCache = cacheNameTypekit;
} else {
// just let response pass through, don"t cache
}
}
if (shouldCache) {
var responseToCache = response.clone();
caches.open(shouldCache)
.then(function (cache) {
var cacheRequest = event.request.clone();
cache.put(cacheRequest, responseToCache);
});
}
return response;
}
);
})
);
});
})();