Repository navigation
Expand file tree
/
Copy pathsw.js
More file actions
66 lines (62 loc) · 2.33 KB
/
Copy pathsw.js
File metadata and controls
66 lines (62 loc) · 2.33 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
/* 資工系畢業學分檢核系統 — Service Worker
策略:stale-while-revalidate — 先回快取(秒開),背景抓新版更新快取,
下次載入就是新的。離線時純走快取。改大版時 bump CACHE 名稱清掉舊快取。 */
const CACHE = 'course-v2.1.0';
/* 安裝時預先快取的核心檔案。
v2.0.3:拿掉 './index.html' — Cloudflare Pages 把 /index.html 永久
重導向到 /,cache.addAll() 抓到 redirected response 會整批 reject,
導致 SW install 失敗、離線不可用。改只快取正規 URL './'。
v2.1.0:加入學期資料覆寫檔 semester-115-1.js。 */
const CORE_ASSETS = [
'./',
'./style.css',
'./app.js',
'./semester-115-1.js',
'./manifest.webmanifest',
'./icon.svg'
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE)
// allSettled:單一檔案抓取失敗不會拖垮整個 install
.then((cache) => Promise.allSettled(
CORE_ASSETS.map((url) => cache.add(url))
))
.then(() => self.skipWaiting())
);
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys()
.then((keys) => Promise.all(
keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))
))
.then(() => self.clients.claim())
);
});
self.addEventListener('fetch', (event) => {
if (event.request.method !== 'GET') return;
event.respondWith(
caches.open(CACHE).then(async (cache) => {
const cached = await cache.match(event.request, { ignoreSearch: true });
// 背景抓新版(成功就更新快取)
const networkFetch = fetch(event.request)
.then((response) => {
if (response && (response.ok || response.type === 'opaque')) {
cache.put(event.request, response.clone());
}
return response;
})
.catch(() => null);
// 有快取就先回快取(背景仍在更新);沒有就等網路;都失敗則 fallback
if (cached) return cached;
const network = await networkFetch;
if (network) return network;
// 離線且沒快取時,導覽請求 fallback 回正規首頁 './'
if (event.request.mode === 'navigate') {
return cache.match('./', { ignoreSearch: true });
}
return new Response('', { status: 504, statusText: 'Offline' });
})
);
});