Repository navigation
Expand file tree
/
Copy pathservice-worker.js
More file actions
65 lines (59 loc) · 1.77 KB
/
Copy pathservice-worker.js
File metadata and controls
65 lines (59 loc) · 1.77 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
const CACHE_VER = 'v1';
const STATIC_CACHE = `weather-clock-static-${CACHE_VER}`;
const API_CACHE = `weather-clock-api-${CACHE_VER}`;
const STATIC_ASSETS = [
'./',
'./index.html',
'./css/style.css',
'./js/app.js',
'./js/clock.js',
'./js/weather.js',
'./js/settings.js',
'./manifest.webmanifest',
'./fonts/DSEG/DSEG7Classic-Regular.woff2',
'./fonts/DSEG/DSEG14Classic-Regular.woff2',
'./icons/icon-192.png',
'./icons/icon-512.png',
];
// ---- インストール: 静的アセットを全キャッシュ ----
self.addEventListener('install', event => {
event.waitUntil(
caches.open(STATIC_CACHE)
.then(cache => cache.addAll(STATIC_ASSETS))
.then(() => self.skipWaiting())
);
});
// ---- アクティベート: 旧キャッシュ削除 ----
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(keys =>
Promise.all(
keys
.filter(k => k !== STATIC_CACHE && k !== API_CACHE)
.map(k => caches.delete(k))
)
).then(() => self.clients.claim())
);
});
// ---- フェッチ: 静的=キャッシュ優先, API=ネットワーク優先 ----
self.addEventListener('fetch', event => {
const url = new URL(event.request.url);
if (url.hostname === 'www.jma.go.jp') {
// JMA API: ネットワーク優先、失敗時はキャッシュ
event.respondWith(
fetch(event.request)
.then(resp => {
const clone = resp.clone();
caches.open(API_CACHE).then(c => c.put(event.request, clone));
return resp;
})
.catch(() => caches.match(event.request))
);
return;
}
// 静的アセット: キャッシュ優先
event.respondWith(
caches.match(event.request)
.then(cached => cached || fetch(event.request))
);
});