Repository navigation
Expand file tree
/
Copy pathsw.js
More file actions
105 lines (95 loc) · 2.87 KB
/
Copy pathsw.js
File metadata and controls
105 lines (95 loc) · 2.87 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
// Service Worker for Grand Grant Matcher
// Provides caching for faster repeat visits
const CACHE_NAME = 'ggm-cache-v5';
// Static assets to cache on install (small files only)
// Large data files (grants.json, reranked_matches.json, etc.) use network-first
// to prevent blocking service worker install on mobile devices
const STATIC_ASSETS = [
'/',
'/index.html',
'/styles.css',
'/script.js',
'/teaser.js'
// Removed large data files to prevent SW install blocking
];
// Data files use network-first with optional caching
const DATA_FILES = [
'/data/grants.json',
'/data/reranked_matches.json',
'/data/affiliation_dict.json',
'/data/collaborations.json',
'/data/matches.json'
];
// Install: cache static assets
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => cache.addAll(STATIC_ASSETS))
.then(() => self.skipWaiting())
);
});
// Activate: clean up old caches
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(keys =>
Promise.all(
keys.filter(key => key !== CACHE_NAME)
.map(key => caches.delete(key))
)
).then(() => self.clients.claim())
);
});
// Check if URL is a data file
function isDataFile(pathname) {
return DATA_FILES.some(file => pathname.endsWith(file));
}
// Fetch: cache-first for static assets, network-first for API and data files
self.addEventListener('fetch', event => {
const url = new URL(event.request.url);
// Network-first for API calls (voting backend)
if (url.origin === 'https://ggm-backend.onrender.com') {
event.respondWith(
fetch(event.request)
.catch(() => caches.match(event.request))
);
return;
}
// Same-origin requests
if (url.origin === self.location.origin) {
// Network-first for large data files (stale-while-revalidate pattern)
if (isDataFile(url.pathname)) {
event.respondWith(
fetch(event.request)
.then(response => {
// Cache the fresh response for offline use
if (response.ok) {
const clone = response.clone();
caches.open(CACHE_NAME).then(cache => {
cache.put(event.request, clone);
});
}
return response;
})
.catch(() => caches.match(event.request))
);
return;
}
// Cache-first for static assets
event.respondWith(
caches.match(event.request)
.then(cached => {
if (cached) return cached;
return fetch(event.request).then(response => {
// Cache successful responses
if (response.ok) {
const clone = response.clone();
caches.open(CACHE_NAME).then(cache => {
cache.put(event.request, clone);
});
}
return response;
});
})
);
}
});