-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathworker.js
More file actions
105 lines (96 loc) · 2.46 KB
/
worker.js
File metadata and controls
105 lines (96 loc) · 2.46 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
100
101
102
103
104
105
/* jshint esversion: 6 */
/* globals self, caches */
const currentCache = '4.7.1';
const assets = [
"/",
"/index.html",
"/styles/main.css",
"/styles/colors.css",
"/scripts/app.js",
"/scripts/clock.js",
"/scripts/calendar.js",
"/libs/suncalc/suncalc.js",
"/libs/astronomy/astronomy.browser.min.js"
];
// install event
self.addEventListener('install', event => {
console.log('Service worker install event', event);
// Cache assets
event.waitUntil(
caches.open(currentCache)
.then(cache => {
console.log('Caching assets');
cache.addAll(assets);
})
.then(() => {
// Skip waiting to activate the new service worker immediately
return self.skipWaiting();
})
);
});
// activate event
self.addEventListener('activate', event => {
console.log('Service worker activate event', event);
// Delete old caches
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheName !== currentCache) {
console.log(`Deleting old cache: ${cacheName}`);
return caches.delete(cacheName); // Delete old caches
}
})
);
}).then(() => {
// Take control of all clients immediately
return self.clients.claim();
})
);
});
// fetch event: network first for HTML, then cache first for assets
self.addEventListener('fetch', event => {
console.log(`Fetching: ${event.request.url}`);
// Network-first for HTML
if (event.request.mode === 'navigate') {
event.respondWith(
fetch(event.request)
.then(response => {
// Cache the new response if it's valid
return caches.open(currentCache).then(cache => {
cache.put(event.request, response.clone());
return response;
});
})
.catch(() => {
// Fallback to cached HTML if network fails
return caches.match('/index.html');
})
);
return;
}
// Cache-first for assets (JS, CSS, images, etc.)
event.respondWith(
caches.match(event.request)
.then(response => {
if (response) {
console.log(`Getting from cache: ${response.url}`);
return response;
}
// If not in cache, fetch and cache it
return fetch(event.request.clone()).then(response => {
if (response.status < 400) {
console.log(`Caching: ${response.url}`);
caches.open(currentCache).then(cache => {
cache.put(event.request, response.clone());
});
}
return response;
});
})
.catch((error) => {
console.error('Error fetching:', error);
throw error;
})
);
});