-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
186 lines (184 loc) · 8.64 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
/**
* Copyright 2016 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ // DO NOT EDIT THIS GENERATED OUTPUT DIRECTLY!
// This file should be overwritten as part of your build process.
// If you need to extend the behavior of the generated service worker, the best approach is to write
// additional code and include it using the importScripts option:
// https://github.com/GoogleChrome/sw-precache#importscripts-arraystring
//
// Alternatively, it's possible to make changes to the underlying template file and then use that as the
// new base for generating output, via the templateFilePath option:
// https://github.com/GoogleChrome/sw-precache#templatefilepath-string
//
// If you go that route, make sure that whenever you update your sw-precache dependency, you reconcile any
// changes made to this original template file with your modified copy.
// This generated service worker JavaScript will precache your site's resources.
// The code needs to be saved in a .js file at the top-level of your site, and registered
// from your pages in order to be used. See
// https://github.com/googlechrome/sw-precache/blob/master/demo/app/js/service-worker-registration.js
// for an example of how you can register this script and handle various service worker events.
/* eslint-env worker, serviceworker */
/* eslint-disable indent, no-unused-vars, no-multiple-empty-lines, max-nested-callbacks, space-before-function-paren, quotes, comma-spacing */
/*Service Worker for providing offline caching and PWA support*/
'use strict';
//Files to cache at page load//
var precacheConfig = [
["style.css"]
];
[
["js/jquery.min.js"]
];
[
["js/bootstrap.min.js"]
];
[
["css/bootstrap.min.css"]
];
[
["js/all.min.js"]
];
[
["js/accessibilitytools.js"]
];
[
["js/theme-plugins.js"]
];
//Cache version control (when value increases cache is cleared and refreshed//
var cacheName = "sw-precache-v6--" + (self.registration ? self.registration.scope : ""),
ignoreUrlParametersMatching = [/^utm_/],
addDirectoryIndex = function (originalUrl, index) {
var url = new URL(originalUrl);
if ("/" === url.pathname.slice(-1)) {
url.pathname += index
}
return url.toString()
},
cleanResponse = function (originalResponse) { // If this is not a redirected response, then we don't have to do anything.
if (!originalResponse.redirected) {
return Promise.resolve(originalResponse)
} // Firefox 50 and below doesn't support the Response.body stream, so we may
// need to read the entire body to memory as a Blob.
var bodyPromise = "body" in originalResponse ? Promise.resolve(originalResponse.body) : originalResponse.blob();
return bodyPromise.then(function (body) { // new Response() is happy when passed either a stream or a Blob.
return new Response(body, {
headers: originalResponse.headers,
status: originalResponse.status,
statusText: originalResponse.statusText
})
})
},
createCacheKey = function (originalUrl, paramName, paramValue, dontCacheBustUrlsMatching) { // Create a new URL object to avoid modifying originalUrl.
var url = new URL(originalUrl); // If dontCacheBustUrlsMatching is not set, or if we don't have a match,
// then add in the extra cache-busting URL parameter.
if (!dontCacheBustUrlsMatching || !url.pathname.match(dontCacheBustUrlsMatching)) {
url.search += (url.search ? "&" : "") + encodeURIComponent(paramName) + "=" + encodeURIComponent(paramValue)
}
return url.toString()
},
isPathWhitelisted = function (whitelist, absoluteUrlString) { // If the whitelist is empty, then consider all URLs to be whitelisted.
if (0 === whitelist.length) {
return !0
} // Otherwise compare each path regex to the path of the URL passed in.
var path = new URL(absoluteUrlString).pathname;
return whitelist.some(function (whitelistedPathRegex) {
return path.match(whitelistedPathRegex)
})
},
stripIgnoredUrlParameters = function (originalUrl, ignoreUrlParametersMatching) {
var url = new URL(originalUrl); // Remove the hash; see https://github.com/GoogleChrome/sw-precache/issues/290
url.hash = "";
url.search = url.search.slice(1) // Exclude initial '?'
.split("&") // Split into an array of 'key=value' strings
.map(function (kv) {
return kv.split("="); // Split each 'key=value' string into a [key, value] array
}).filter(function (kv) {
return ignoreUrlParametersMatching.every(function (ignoredRegex) {
return !ignoredRegex.test(kv[0]); // Return true iff the key doesn't match any of the regexes.
})
}).map(function (kv) {
return kv.join("="); // Join each [key, value] array into a 'key=value' string
}).join("&"); // Join the array of 'key=value' strings into a string with '&' in between each
return url.toString()
},
hashParamName = "_sw-precache",
urlsToCacheKeys = new Map(precacheConfig.map(function (item) {
var relativeUrl = item[0],
hash = item[1],
absoluteUrl = new URL(relativeUrl, self.location),
cacheKey = createCacheKey(absoluteUrl, hashParamName, hash, !1);
return [absoluteUrl.toString(), cacheKey]
}));
function setOfCachedUrls(cache) {
return cache.keys().then(function (requests) {
return requests.map(function (request) {
return request.url
})
}).then(function (urls) {
return new Set(urls)
})
}
self.addEventListener("install", function (event) {
event.waitUntil(caches.open(cacheName).then(function (cache) {
return setOfCachedUrls(cache).then(function (cachedUrls) {
return Promise.all(Array.from(urlsToCacheKeys.values()).map(function (cacheKey) { // If we don't have a key matching url in the cache already, add it.
if (!cachedUrls.has(cacheKey)) {
var request = new Request(cacheKey, {
credentials: "same-origin"
});
return fetch(request).then(function (response) { // Bail out of installation unless we get back a 200 OK for
// every request.
if (!response.ok) {
throw new Error("Request for " + cacheKey + " returned a " + "response with status " + response.status)
}
return cleanResponse(response).then(function (responseToCache) {
return cache.put(cacheKey, responseToCache)
})
})
}
}))
})
}).then(function () { // Force the SW to transition from installing -> active state
return self.skipWaiting()
}))
});
self.addEventListener("activate", function (event) {
var setOfExpectedUrls = new Set(urlsToCacheKeys.values());
event.waitUntil(caches.open(cacheName).then(function (cache) {
return cache.keys().then(function (existingRequests) {
return Promise.all(existingRequests.map(function (existingRequest) {
if (!setOfExpectedUrls.has(existingRequest.url)) {
return cache.delete(existingRequest)
}
}))
})
}).then(function () {
return self.clients.claim()
}))
});
self.addEventListener("fetch", function (event) {
if ("GET" === event.request.method) { // Should we call event.respondWith() inside this fetch event handler?
// This needs to be determined synchronously, which will give other fetch
// handlers a chance to handle the request if need be.
var shouldRespond, url = stripIgnoredUrlParameters(event.request.url, ignoreUrlParametersMatching); // First, remove all the ignored parameters and hash fragment, and see if we
// have that URL in our cache. If so, great! shouldRespond will be true.
shouldRespond = urlsToCacheKeys.has(url); // If shouldRespond is false, check again, this time with 'index.html'
// (or whatever the directoryIndex option is set to) at the end.
var directoryIndex = "";
if (!shouldRespond && directoryIndex) {
url = addDirectoryIndex(url, directoryIndex);
shouldRespond = urlsToCacheKeys.has(url)
}
}
});