-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsw.js
More file actions
83 lines (72 loc) · 2.8 KB
/
sw.js
File metadata and controls
83 lines (72 loc) · 2.8 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
const CACHE_NAME = '8-ball-pool-dynamic-cache-v3';
const version = 'v1.985';
let lastRequestTime = Date.now();
// Installs the service worker and activates it immediately.
self.addEventListener('install', event => {
self.skipWaiting();
});
// Activates the new service worker, cleans non-static assets from the cache, and notifies clients to reload.
self.addEventListener('activate', event => {
const cleanupAndNotifyClients = async () => {
try {
const cacheNames = await caches.keys();
const cleanupPromises = cacheNames.map(async (cacheName) => {
const cache = await caches.open(cacheName);
const requests = await cache.keys();
const deletePromises = requests.map(async (request) => {
const url = new URL(request.url);
if (!url.hostname.includes('static')) {
await cache.delete(request);
}
});
await Promise.all(deletePromises);
});
await Promise.all(cleanupPromises);
await self.clients.claim();
const clientsArr = await self.clients.matchAll({
type: 'window'
});
clientsArr.forEach(client => {
client.postMessage({
type: 'SW_UPDATED'
});
});
} catch (error) { // Intentionally silent in production.
}
}
event.waitUntil(cleanupAndNotifyClients());
});
// Handles network requests using a cache-first strategy, excluding analytics and tracking scripts.
self.addEventListener('fetch', event => {
lastRequestTime = Date.now();
if (event.request.method !== 'GET' || !event.request.url.includes('static')) {
return;
}
const respond = async () => {
if (event.request.url.includes('game.wasm')) {
await new Promise(resolve => {
const checkIdle = () => {
if (Date.now() - lastRequestTime >= 1000) {
resolve();
} else {
setTimeout(checkIdle, 100);
}
};
checkIdle();
});
}
const cachedResponse = await caches.match(event.request);
if (cachedResponse) {
return cachedResponse;
}
const networkResponse = await fetch(event.request);
if (!networkResponse || (networkResponse.status !== 200 && networkResponse.status !== 0)) {
return networkResponse;
}
const responseToCache = networkResponse.clone();
const cache = await caches.open(CACHE_NAME);
await cache.put(event.request, responseToCache);
return networkResponse;
}
event.respondWith(respond());
});