-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice-worker.js
More file actions
99 lines (92 loc) · 2.58 KB
/
service-worker.js
File metadata and controls
99 lines (92 loc) · 2.58 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
95
96
97
98
99
const CACHE_NAME = 'aemo-dev-v2.1.0';
const STATIC_ASSETS = [
'/',
'/index.html',
'/manifest.json',
'/assets/images/icon.png',
'/assets/images/ai2-logo.png',
'/assets/images/kodular-logo.png',
'/assets/images/telegram-logo.webp'
];
// Install event - cache static assets
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => {
console.log('[SW] Caching static assets');
return cache.addAll(STATIC_ASSETS);
})
.catch(err => {
console.error('[SW] Cache failed:', err);
})
);
self.skipWaiting();
});
// Activate event - clean up old caches
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames
.filter(name => name !== CACHE_NAME)
.map(name => {
console.log('[SW] Deleting old cache:', name);
return caches.delete(name);
})
);
})
);
self.clients.claim();
});
// Fetch event - serve cached content when offline
self.addEventListener('fetch', (event) => {
const { request } = event;
const url = new URL(request.url);
// Skip non-GET requests
if (request.method !== 'GET') {
return;
}
// Skip API calls
if (url.pathname.startsWith('/api/')) {
return;
}
// Cache strategy: Stale While Revalidate for assets, Network First for HTML
if (request.mode === 'navigate' || url.pathname.endsWith('.html')) {
// Network First for HTML
event.respondWith(
fetch(request)
.then(response => {
if (response.ok) {
const clone = response.clone();
caches.open(CACHE_NAME).then(cache => {
cache.put(request, clone);
});
}
return response;
})
.catch(() => {
return caches.match(request).then(cached => {
return cached || new Response('Offline', { status: 503 });
});
})
);
} else {
// Stale While Revalidate for assets
event.respondWith(
caches.match(request).then(cached => {
const fetchPromise = fetch(request)
.then(response => {
if (response.ok && response.type !== 'opaque') {
const clone = response.clone();
caches.open(CACHE_NAME).then(cache => {
cache.put(request, clone);
});
}
return response;
})
.catch(() => cached || new Response('Offline', { status: 503 }));
return cached || fetchPromise;
})
);
}
});