-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
94 lines (81 loc) · 2.46 KB
/
Copy pathsw.js
File metadata and controls
94 lines (81 loc) · 2.46 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
const SHELL_CACHE = 'lmn-shell-v1';
const RUNTIME_TILE_CACHE = 'lmn-tiles-v1';
const RUNTIME_DATA_CACHE = 'lmn-data-v1';
const SHELL_FILES = [
'./',
'index.html',
'desktop-main.html',
'mobile-main.html',
'mobile-results.html',
'mobile-search.html',
'mobile-saved.html',
'mobile-profile.html',
'lmn-core.js',
'manifest.webmanifest',
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(SHELL_CACHE).then((cache) => cache.addAll(SHELL_FILES)).then(() => self.skipWaiting())
);
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(
keys
.filter((key) => ![SHELL_CACHE, RUNTIME_TILE_CACHE, RUNTIME_DATA_CACHE].includes(key))
.map((key) => caches.delete(key))
)
).then(() => self.clients.claim())
);
});
async function staleWhileRevalidate(request, cacheName) {
const cache = await caches.open(cacheName);
const cached = await cache.match(request);
const networkFetch = fetch(request)
.then((response) => {
if (response && response.status === 200) {
cache.put(request, response.clone());
}
return response;
})
.catch(() => null);
return cached || networkFetch || new Response('', { status: 504, statusText: 'Offline' });
}
async function cacheFirst(request, cacheName) {
const cache = await caches.open(cacheName);
const cached = await cache.match(request);
if (cached) return cached;
try {
const response = await fetch(request);
if (response && response.status === 200) {
cache.put(request, response.clone());
}
return response;
} catch {
return new Response('', { status: 504, statusText: 'Offline' });
}
}
self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url);
if (event.request.method !== 'GET') {
return;
}
// App shell and same-origin static files
if (url.origin === self.location.origin) {
event.respondWith(cacheFirst(event.request, SHELL_CACHE));
return;
}
// OSM tiles: cache first for offline usability
if (url.hostname.includes('tile.openstreetmap.org')) {
event.respondWith(cacheFirst(event.request, RUNTIME_TILE_CACHE));
return;
}
// Geocoding/POI data: stale-while-revalidate
if (
url.hostname.includes('nominatim.openstreetmap.org') ||
url.hostname.includes('overpass-api.de')
) {
event.respondWith(staleWhileRevalidate(event.request, RUNTIME_DATA_CACHE));
}
});