DawnC commited on
Commit
0f17dbc
·
verified ·
1 Parent(s): 026220a

Update service-worker.js

Browse files
Files changed (1) hide show
  1. service-worker.js +29 -36
service-worker.js CHANGED
@@ -1,44 +1,37 @@
1
- const CACHE_NAME = 'pawmatch-v1';
 
 
2
  const urlsToCache = [
3
- '/',
4
- '/manifest.json',
5
- '/icon-192.png',
6
- '/icon-512.png'
7
  ];
8
 
9
  self.addEventListener('install', (event) => {
10
- event.waitUntil(
11
- Promise.all([
12
- caches.open(CACHE_NAME).then((cache) => {
13
- return cache.addAll(urlsToCache);
14
- }),
15
- self.skipWaiting()
16
- ])
17
- );
18
- });
19
-
20
- self.addEventListener('activate', (event) => {
21
- event.waitUntil(
22
- Promise.all([
23
- caches.keys().then((cacheNames) => {
24
- return Promise.all(
25
- cacheNames
26
- .filter((cacheName) => cacheName !== CACHE_NAME)
27
- .map((cacheName) => caches.delete(cacheName))
28
- );
29
- }),
30
- self.clients.claim()
31
- ])
32
- );
33
  });
34
 
35
  self.addEventListener('fetch', (event) => {
36
- event.respondWith(
37
- caches.match(event.request).then((response) => {
38
- if (response) {
39
- return response;
40
- }
41
- return fetch(event.request);
42
- })
43
- );
 
 
 
 
 
44
  });
 
1
+ const CACHE_NAME = 'pawmatch-v2';
2
+ const BASE_URL = self.location.pathname.replace('service-worker.js', '');
3
+
4
  const urlsToCache = [
5
+ BASE_URL,
6
+ `${BASE_URL}manifest.json`,
7
+ `${BASE_URL}icon-192.png`,
8
+ `${BASE_URL}icon-512.png`
9
  ];
10
 
11
  self.addEventListener('install', (event) => {
12
+ event.waitUntil(
13
+ caches.open(CACHE_NAME)
14
+ .then((cache) => {
15
+ console.log('Cache opened');
16
+ return cache.addAll(urlsToCache);
17
+ })
18
+ .then(() => self.skipWaiting())
19
+ .catch(error => console.error('Cache error:', error))
20
+ );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  });
22
 
23
  self.addEventListener('fetch', (event) => {
24
+ event.respondWith(
25
+ caches.match(event.request)
26
+ .then((response) => {
27
+ if (response) {
28
+ return response;
29
+ }
30
+ return fetch(event.request);
31
+ })
32
+ .catch(() => {
33
+ // 如果離線且快取中沒有,返回離線頁面或預設內容
34
+ return new Response('Offline');
35
+ })
36
+ );
37
  });