-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
197 lines (178 loc) · 7.73 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
187
188
189
190
191
192
193
194
195
196
197
//
// MIT License
//
// Copyright (c) 2020 Carlos Rafael Gimenes das Neves
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// https://github.com/carlosrafaelgn/pixel
//
"use strict";
// Change this value to force the browser to install the
// service worker again, and recreate the cache (this technique
// works because the browser reinstalls the service worker
// whenever it detects a change in the source code of the
// service worker).
const CACHE_PREFIX = "pixel-static-cache";
const CACHE_VERSION = "-20210513";
const CACHE_NAME = CACHE_PREFIX + CACHE_VERSION;
self.addEventListener("install", (event) => {
// skipWaiting() will force the browser to start using
// this version of the service worker as soon as its
// installation finishes.
// It does not really matter when we call skipWaiting(),
// as long as we perform all other operations inside
// event.waitUntil(). Calling event.waitUntil() forces
// the installation process to be marked as finished
// only when all promises passed to waitUntil() finish.
self.skipWaiting();
event.waitUntil(caches.open(CACHE_NAME).then((cache) => {
// According to the spec, the service worker file
// is handled differently by the browser and needs
// not to be added to the cache. I tested it and I
// confirm the service worker works offline even when
// not present in the cache (despite the error message
// displayed by the browser when trying to fetch it).
//
// Also, there is no need to worry about max-age and
// other cache-control headers/settings, because the
// CacheStorage API ignores them.
//
// Nevertheless, even though CacheStorage API ignores
// them, tests showed that a in few occasions, when
// the browser was fetching these files, the file
// being added to the cache actually came from the
// browser's own cache... Therefore, I switched from
// cache.addAll() to this.
//
// Let the commented files be downloaded/cached only
// if the browser requests them!
const files = [
"/pixel/",
"/pixel/assets/favicons/favicon-512x512.png",
"/pixel/assets/favicons/manifest.webmanifest",
//"/pixel/assets/fonts/PressStart2P-Regular.ttf",
"/pixel/assets/fonts/PressStart2P-Regular.woff2",
"/pixel/assets/images/fade.png",
"/pixel/assets/images/fixed-bg.png",
"/pixel/assets/images/grid1.png",
"/pixel/assets/images/grid2.png",
"/pixel/assets/images/grid3.png",
"/pixel/assets/images/grid4.png",
"/pixel/assets/images/grid5.png",
"/pixel/assets/images/loading.gif",
"/pixel/assets/images/logo.png",
"/pixel/assets/images/sheet.png",
"/pixel/assets/images/uiSheet.png",
//"/pixel/assets/js/lib-nowasm.js",
"/pixel/assets/js/lib.js",
//"/pixel/assets/js/lib.js.mem",
"/pixel/assets/js/lib.wasm",
"/pixel/assets/js/levels.js",
"/pixel/assets/js/scripts.min.js"
];
const promises = new Array(files.length);
for (let i = files.length - 1; i >= 0; i--)
promises[i] = cache.add(new Request(files[i], { cache: "no-store" }));
return Promise.all(promises);
}));
});
self.addEventListener("activate", (event) => {
// claim() is used to ask the browser to use this instance
// of the service worker with all possible clients, including
// any pages that might have been opened before this service
// worker was downloaded/activated.
self.clients.claim();
event.waitUntil(
// List all cache storages in our domain.
caches.keys().then(function (keyList) {
// Create one Promise for deleting each cache storage that is not
// our current cache storage, taking care not to delete other
// cache storages from the domain by checking the key prefix (we
// are not using map() to avoid inserting undefined into the array).
const oldCachesPromises = [];
for (let i = keyList.length - 1; i >= 0; i--) {
const key = keyList[i];
if (key.startsWith(CACHE_PREFIX) && key !== CACHE_NAME)
oldCachesPromises.push(caches.delete(key));
}
return Promise.all(oldCachesPromises);
})
);
});
self.addEventListener("fetch", (event) => {
// https://developer.mozilla.org/en-US/docs/Web/API/Request
// mode is navigate only for the document itself (/pixel/ or
// index.html), whereas for all other requests, mode is cors,
// no-cors and so on. So, in order to make the entire game
// work offline we must handle all kinds of requests!
// This will speed up the loading time after the first
// time the user loads the game. The downside of this
// technique is that we will work with an outdated
// version of the resource if it has been changed at
// the server, but has not yet been updated in our
// local cache (which, right now, will only happen
// when the service worker is reinstalled).
event.respondWith(caches.open(CACHE_NAME).then((cache) => {
return cache.match(event.request).then((response) => {
// Return the resource if it has been found.
if (response)
return response;
// When the resource was not found in the cache,
// try to fetch it from the network. We are cloning the
// request because requests are streams, and fetch will
// consume this stream, rendering event.request unusable
// (but we will need a usable request later, for cache.put)
return fetch(event.request.clone()).then((response) => {
// If this fetch succeeds, store it in the cache for
// later! (This means we probably forgot to add a file
// to the cache during the installation phase)
// Just as requests, responses are streams and we will
// need two usable streams: one to be used by the cache
// and one to be returned to the browser! So, we send a
// clone of the response to the cache.
if (response && response.status === 200)
return cache.put(event.request, response.clone()).then(() => {
return response;
}, () => {
// If anything goes wrong, just ignore and try
// to add the response to the cache later.
return response;
});
return response;
}, () => {
// The request was neither in our cache nor was it
// available from the network (maybe we are offline).
// Therefore, try to fulfill requests for favicons with
// the largest favicon we have available in our cache.
if (event.request.url.indexOf("favicon") >= 0)
return cache.match("/pixel/assets/favicons/favicon-512x512.png");
// The resource was not in our cache, was not available
// from the network and was also not a favicon...
// Unfortunately, there is nothing else we can do :(
return null;
});
});
}));
});
// References:
// https://developers.google.com/web/fundamentals/primers/service-workers/?hl=en-us
// https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle?hl=en-us
// https://developers.google.com/web/fundamentals/codelabs/offline/?hl=en-us
// https://web.dev/service-workers-cache-storage