forked from PrimalHQ/primal-web-app
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimageCacheWorker.js
More file actions
93 lines (78 loc) · 2.5 KB
/
imageCacheWorker.js
File metadata and controls
93 lines (78 loc) · 2.5 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
const IMAGE_CACHE = 'images-v1';
const DAY = 1000 * 60 * 60 * 24;
let imageToElementMap = {};
// Install event - precache critical images
self.addEventListener('install', event => {
event.waitUntil(
caches.open(IMAGE_CACHE).then(async (cache) => {
// Fetch the manifest
const manifestResponse = await fetch('/manifest.json');
const manifest = await manifestResponse.json();
// Extract asset URLs from manifest
const assetUrls = Object.values(manifest)
.filter(entry => entry.file && entry.file.match(/\.(png|jpg|jpeg|svg|webp)$/))
.map(entry => `/${entry.file}`);
const uniqueAssetUrls = [...new Set(assetUrls)];
return cache.addAll(uniqueAssetUrls);
}).catch((e => {
if (self.location.hostname === 'localhost') {
console.log('Error prefetching cached images: ', e);
}
}))
);
});
self.addEventListener('activate', event => {
if (self.location.hostname === 'localhost') {
console.log('V1 now ready to handle fetches!');
}
});
// Fetch event - intercept image requests
self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url);
const isLocal = url.origin === location.origin;
if (event.request.destination === 'image') {
event.respondWith(
caches.open(IMAGE_CACHE).then(cache => {
return cache.match(event.request).then(response => {
if (response) {
return response;
}
if (isLocal) {
// Fetch fresh image
return fetch(event.request).then(fetchResponse => {
cache.put(event.request, fetchResponse.clone());
return fetchResponse;
}).catch(error => {
// console.error('FAILED TO FETCH IMAGE: ', url);
});
}
return fetch(event.request).then(fetchResponse => {
return fetchResponse;
}).catch(error => {
// console.error('FAILED TO FETCH IMAGE: ', url);
});
});
})
);
}
});
self.addEventListener('message', event => {
if (event.data.type === 'CACHE_AVATAR' && typeof event.data.url === 'string') {
const url = event.data.url;
event.waitUntil(new Promise(async (resolve) => {
const cache = await caches.open(IMAGE_CACHE);
const response = await cache.match(url);
if (!!response) {
resolve();
}
else {
try {
await cache.add(url);
resolve();
} catch {
resolve();
}
}
}));
}
});