-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
68 lines (65 loc) · 1.91 KB
/
sw.js
File metadata and controls
68 lines (65 loc) · 1.91 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
const CACHE_NAME = 'ganjena-v1_1_8';
const urlsToCache = [
'/ganjena/',
'/ganjena/index.html',
'/ganjena/style.css',
'/ganjena/script.js',
'/ganjena/maintenance.js',
'/ganjena/data/dictionary.json',
'/ganjena/icons/favicon.ico',
'/ganjena/icons/icon-192x192.png',
'/ganjena/icons/icon-512x512.png'
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('fetch', (event) => {
const requestUrl = new URL(event.request.url);
if (requestUrl.pathname === '/ganjena/data/dictionary.json') {
// Cache-then-network strategy for dictionary.json
event.respondWith(
caches.open(CACHE_NAME).then((cache) =>
caches.match(event.request).then((cachedResponse) =>
fetch(event.request)
.then((networkResponse) => {
// Update cache with new response
cache.put(event.request, networkResponse.clone());
return networkResponse;
})
.catch(() => {
// If offline, return cached response
return cachedResponse || new Response(JSON.stringify({ error: 'Offline, using cached data' }), {
status: 503,
statusText: 'Service Unavailable'
});
})
)
)
);
} else {
// Cache-first for other resources
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request);
})
);
}
});
self.addEventListener('activate', (event) => {
const cacheWhitelist = [CACHE_NAME];
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (!cacheWhitelist.includes(cacheName)) {
return caches.delete(cacheName);
}
})
);
})
);
});