forked from cs-util/TemplateJs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice-worker.js
More file actions
98 lines (84 loc) · 2.32 KB
/
service-worker.js
File metadata and controls
98 lines (84 loc) · 2.32 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
const CACHE_NAME = 'snap2map-shell-v2';
const SHELL_ASSETS = [
'/',
'/index.html',
'/src/index.js',
'/service-worker.js',
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches
.open(CACHE_NAME)
.then((cache) => cache.addAll(SHELL_ASSETS))
.catch(() => null)
.finally(() => self.skipWaiting()),
);
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches
.keys()
.then((keys) => Promise.all(keys.filter((key) => key !== CACHE_NAME).map((key) => caches.delete(key))))
.then(() => self.clients.claim()),
);
});
self.addEventListener('fetch', (event) => {
if (event.request.method !== 'GET') {
return;
}
const url = new URL(event.request.url);
const isSameOrigin = url.origin === self.location.origin;
const isNavigation = event.request.mode === 'navigate';
const isShellResource = isSameOrigin && SHELL_ASSETS.includes(url.pathname);
if (!isSameOrigin) {
return;
}
event.respondWith(
caches.open(CACHE_NAME).then(async (cache) => {
const cached = await cache.match(event.request);
const fetchAndUpdate = async () => {
const response = await fetch(event.request);
if (response && response.ok) {
cache.put(event.request, response.clone());
}
return response;
};
const getNavigationFallback = async () => {
const fallback = (await cache.match('/index.html')) || (await cache.match('/'));
return fallback || null;
};
if (isNavigation || isShellResource) {
try {
const response = await fetchAndUpdate();
if (response) {
return response;
}
} catch (error) {
// network request failed, fall back to cache if possible
}
if (cached) {
return cached;
}
if (isNavigation) {
const fallback = await getNavigationFallback();
if (fallback) {
return fallback;
}
}
return Response.error();
}
if (cached) {
fetchAndUpdate().catch(() => null);
return cached;
}
try {
return await fetchAndUpdate();
} catch (error) {
if (cached) {
return cached;
}
return Response.error();
}
}),
);
});