|
1 | 1 | const cacheName = 'my-cache';
|
2 | 2 |
|
3 |
| -async function fetchAndCacheIfOk(event, stale) { |
| 3 | +async function revalidate(event) { |
| 4 | + const client = await clients.get(event.clientId); |
| 5 | + client.postMessage({ type: 'cache' }); |
| 6 | +} |
| 7 | + |
| 8 | +async function fetchAndCacheIfOk(cache, event) { |
4 | 9 | try {
|
5 | 10 | const response = await fetch(event.request);
|
6 | 11 |
|
7 | 12 | if (response.ok) {
|
8 |
| - const responseClone = response.clone(); |
9 |
| - const cache = await caches.open(cacheName); |
10 |
| - await cache.put(event.request, responseClone); |
11 |
| - if (stale) self.postMessage({ type: 'cache' }); |
| 13 | + await cache.put(event.request, response.clone()); |
12 | 14 | }
|
13 | 15 |
|
14 | 16 | return response;
|
15 | 17 | } catch (e) {
|
16 |
| - const cache = await caches.open(cacheName); |
| 18 | + console.error(e); |
| 19 | + |
17 | 20 | return await cache.match('/index.html');
|
18 | 21 | }
|
19 | 22 | }
|
20 | 23 |
|
21 | 24 | async function fetchWithCache(event) {
|
22 | 25 | const cache = await caches.open(cacheName);
|
23 | 26 | const response = await cache.match(event.request);
|
24 |
| - const result = fetchAndCacheIfOk(event, !!response); |
| 27 | + const result = fetchAndCacheIfOk(cache, event); |
25 | 28 | if (!!response) {
|
26 |
| - return response; |
| 29 | + result.then(async (response2) => { |
| 30 | + const reader1 = response.body.getReader(); |
| 31 | + const reader2 = response2.body.getReader(); |
| 32 | + |
| 33 | + let i = 0; |
| 34 | + let j = 0; |
| 35 | + |
| 36 | + let oldChunk1 = null; |
| 37 | + let oldChunk2 = null; |
| 38 | + if (!oldChunk1) { |
| 39 | + oldChunk1 = await reader1.read(); |
| 40 | + } |
| 41 | + if (!oldChunk2) { |
| 42 | + oldChunk2 = await reader2.read(); |
| 43 | + } |
| 44 | + while (!oldChunk1.done && !oldChunk2.done) { |
| 45 | + if (oldChunk1.value[i] !== oldChunk2.value[j]) { |
| 46 | + revalidate(event); |
| 47 | + return; |
| 48 | + } |
| 49 | + i++; |
| 50 | + j++; |
| 51 | + if (i === oldChunk1.value.length) { |
| 52 | + oldChunk1 = await reader1.read(); |
| 53 | + i = 0; |
| 54 | + } |
| 55 | + if (j === oldChunk2.value.length) { |
| 56 | + oldChunk2 = await reader2.read(); |
| 57 | + j = 0; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + if (oldChunk1.done && oldChunk2.done) { |
| 62 | + return; |
| 63 | + } else { |
| 64 | + revalidate(event); |
| 65 | + return; |
| 66 | + } |
| 67 | + }); |
| 68 | + |
| 69 | + return response.clone(); |
27 | 70 | } else {
|
28 | 71 | return result;
|
29 | 72 | }
|
|
0 commit comments