-
Notifications
You must be signed in to change notification settings - Fork 0
/
service-worker.js
63 lines (57 loc) · 1.52 KB
/
service-worker.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
const CACHE_NAME = 'my-cache2';
const FILES_TO_CACHE = [
'/',
'/index.html',
'/worker.js',
'/main.js',
'/hunter.png'
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
console.log('Opened cache:', CACHE_NAME);
return cache.addAll(FILES_TO_CACHE);
})
);
});
self.addEventListener('activate', (event) => {
console.log('Service Worker activated');
event.waitUntil(
caches.keys().then((cacheNames) => {
console.log('cacheNames', cacheNames)
return Promise.all(
cacheNames.map((cacheName) => {
console.log('cacheName', cacheName)
if (cacheName !== CACHE_NAME) {
console.log('Deleting old cache:', cacheName);
return caches.delete(cacheName);
}
})
);
})
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((cachedResponse) => {
if (cachedResponse) {
console.log('Serving from cache:', event.request.url);
return cachedResponse;
}
console.log('Fetching from network:', event.request.url);
return fetch(event.request);
})
);
});
// service-worker.js
self.addEventListener('sync', (event) => {
if (event.tag === 'my-sync') {
console.log('Performing background sync');
event.waitUntil(syncData());
}
});
async function syncData() {
console.log('syncing ...')
return "synced"
// Perform the data synchronization here
}