-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw.js
86 lines (80 loc) · 2.71 KB
/
sw.js
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
// Cache version - change this to force cache refresh
const CACHE_VERSION = '15';
const CACHE_NAME = `omnicart-v${CACHE_VERSION}`;
const ASSETS_TO_CACHE = [
'/',
'./index.html',
'./styles.css',
'./app.js',
'./manifest.json',
'./icons/icon-192x192.png',
'./icons/icon-512x512.png'
];
// Install event - cache assets
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => cache.addAll(ASSETS_TO_CACHE))
.then(() => self.skipWaiting()) // Force activation
);
});
// Activate event - clean up old caches
self.addEventListener('activate', event => {
event.waitUntil(
Promise.all([
// Clean up old caches
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheName !== CACHE_NAME) {
return caches.delete(cacheName);
}
})
);
}),
// Take control of all clients immediately
self.clients.claim()
])
);
});
// Fetch event - network first for HTML, cache first for other assets
self.addEventListener('fetch', event => {
// Parse the URL
const requestURL = new URL(event.request.url);
// Network-first strategy for HTML files to ensure fresh content
if (requestURL.pathname.endsWith('.html') || requestURL.pathname.endsWith('/')) {
event.respondWith(
fetch(event.request)
.then(response => {
const clonedResponse = response.clone();
caches.open(CACHE_NAME).then(cache => {
cache.put(event.request, clonedResponse);
});
return response;
})
.catch(() => {
return caches.match(event.request);
})
);
return;
}
// Cache-first strategy for other assets
event.respondWith(
caches.match(event.request)
.then(response => {
if (response) {
return response;
}
return fetch(event.request).then(response => {
// Don't cache API calls
if (event.request.url.includes('api.mymemory.translated.net')) {
return response;
}
return caches.open(CACHE_NAME).then(cache => {
cache.put(event.request, response.clone());
return response;
});
});
})
);
});