-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathsw.js
More file actions
94 lines (86 loc) · 3.08 KB
/
sw.js
File metadata and controls
94 lines (86 loc) · 3.08 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
91
92
93
94
const CACHE_VERSION = Date.now(); // Auto-bust cache on new SW install
const CACHE_NAME = `os-compass-v4-${CACHE_VERSION}`;
const OFFLINE_PAGE = './offline.html';
const ASSETS_TO_CACHE = [
'./',
'./index.html',
'./offline.html',
'./frontend/css/style.css',
'./frontend/css/home.css',
'./frontend/js/components.js',
'./frontend/js/theme.js',
'./frontend/js/home.js',
'./manifest.json',
'./frontend/library/assets/logo.png',
'./frontend/library/assets/favicon.png',
'./public/icon.png'
];
/* INSTALL - Skip waiting immediately to activate the new SW */
self.addEventListener('install', (event) => {
self.skipWaiting();
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
console.log('Caching assets with version:', CACHE_NAME);
return cache.addAll(ASSETS_TO_CACHE);
})
);
});
/* ACTIVATE - Delete ALL old caches and claim clients */
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (cacheName !== CACHE_NAME) {
console.log('Deleting old cache:', cacheName);
return caches.delete(cacheName);
}
})
);
}).then(() => {
console.log('New service worker activated, claiming clients');
return self.clients.claim();
})
);
});
/* FETCH - Network-first strategy: always try to get fresh content */
self.addEventListener('fetch', (event) => {
const request = event.request;
// Only handle GET requests
if (request.method !== 'GET') return;
// Skip non-http(s) requests (e.g. chrome-extension://)
if (!request.url.startsWith('http')) return;
// Handle navigation (HTML pages) - Network first, fallback to cache/offline
if (request.mode === 'navigate') {
event.respondWith(
fetch(request)
.then((response) => {
const copy = response.clone();
caches.open(CACHE_NAME).then((cache) => {
cache.put(request, copy);
});
return response;
})
.catch(() => caches.match(request).then(res => res || caches.match(OFFLINE_PAGE)))
);
return;
}
// Handle all other assets (CSS, JS, images, fonts, etc.) - Network first
event.respondWith(
fetch(request)
.then((response) => {
// Only cache successful, same-origin or CORS responses
if (response && response.status === 200) {
const copy = response.clone();
caches.open(CACHE_NAME).then((cache) => {
cache.put(request, copy);
});
}
return response;
})
.catch(() => {
// Network failed, fallback to cache
return caches.match(request);
})
);
});