-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice-worker.js
106 lines (96 loc) · 3.29 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
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
100
101
102
103
104
105
106
const CACHE_NAME = 'nomad-coffee-v1';
const STATIC_CACHE = 'static-v1';
const DYNAMIC_CACHE = 'dynamic-v1';
const RUNTIME_CACHE = 'runtime-v1';
const STATIC_ASSETS = [
'/',
'/index.html',
'/styles/main.css',
'/styles/hero.css',
'https://unpkg.com/react@18/umd/react.production.min.js',
'https://unpkg.com/react-dom@18/umd/react-dom.production.min.js',
'https://unpkg.com/@babel/standalone/babel.min.js',
'https://cdn.tailwindcss.com'
];
const DYNAMIC_ASSETS = [
'/styles/header.css',
'/styles/products.css',
'/styles/footer.css',
'/styles/animations.css',
'/styles/cart.css',
'/styles/about.css',
'/styles/locations.css',
'/styles/contact.css'
];
self.addEventListener('install', event => {
event.waitUntil(
Promise.all([
caches.open(STATIC_CACHE).then(cache => cache.addAll(STATIC_ASSETS)),
caches.open(DYNAMIC_CACHE).then(cache => cache.addAll(DYNAMIC_ASSETS))
])
);
});
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames
.filter(cacheName =>
cacheName.startsWith('nomad-') &&
![STATIC_CACHE, DYNAMIC_CACHE, RUNTIME_CACHE].includes(cacheName)
)
.map(cacheName => caches.delete(cacheName))
);
})
);
});
self.addEventListener('fetch', event => {
// Skip cross-origin requests
if (!event.request.url.startsWith(self.location.origin)) {
return;
}
event.respondWith(
caches.match(event.request)
.then(cachedResponse => {
if (cachedResponse) {
// Return cached response and update cache in background
if (navigator.onLine) {
fetch(event.request)
.then(response => {
if (response.ok) {
caches.open(RUNTIME_CACHE)
.then(cache => cache.put(event.request, response));
}
});
}
return cachedResponse;
}
return fetch(event.request)
.then(response => {
if (!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
const responseToCache = response.clone();
caches.open(RUNTIME_CACHE)
.then(cache => {
cache.put(event.request, responseToCache);
});
return response;
});
})
);
});
// Cache cleanup
self.addEventListener('message', event => {
if (event.data === 'clearOldCaches') {
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheName !== CACHE_NAME) {
return caches.delete(cacheName);
}
})
);
});
}
});