-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
90 lines (77 loc) · 2.65 KB
/
sw.js
File metadata and controls
90 lines (77 loc) · 2.65 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
/* ─────────────────────────────────────────────
RRPL Remote Arm — Service Worker (PWA)
───────────────────────────────────────────── */
'use strict';
const CACHE_NAME = 'rrpl-remote-arm-v2';
// All local assets to pre-cache on install
const LOCAL_ASSETS = [
'./',
'./index.html',
'./styles.css',
'./app.js',
'./manifest.json',
];
// ── Install: pre-cache local assets ──────────
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => cache.addAll(LOCAL_ASSETS))
.then(() => self.skipWaiting())
);
});
// ── Activate: purge old caches ────────────────
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())
);
});
// ── Fetch: cache-first for local, network-first
// for Google Fonts (so updates land) ──
self.addEventListener('fetch', event => {
const url = new URL(event.request.url);
// Google Fonts — stale-while-revalidate
if (url.hostname === 'fonts.googleapis.com' || url.hostname === 'fonts.gstatic.com') {
event.respondWith(staleWhileRevalidate(event.request));
return;
}
// Everything else — cache-first with network fallback
event.respondWith(cacheFirst(event.request));
});
// ── Strategies ────────────────────────────────
async function cacheFirst(request) {
const cached = await caches.match(request);
if (cached) return cached;
try {
const response = await fetch(request);
if (response.ok) {
const cache = await caches.open(CACHE_NAME);
cache.put(request, response.clone());
}
return response;
} catch {
// Offline and not cached — return a minimal offline page for navigations
if (request.mode === 'navigate') {
return caches.match('./index.html');
}
return new Response('Offline', { status: 503 });
}
}
async function staleWhileRevalidate(request) {
const cache = await caches.open(CACHE_NAME);
const cached = await cache.match(request);
const networkFetch = fetch(request)
.then(response => {
if (response.ok) cache.put(request, response.clone());
return response;
})
.catch(() => null);
return cached || networkFetch;
}