Skip to content

Commit c85aec0

Browse files
Use cache.addAll
1 parent ae66ba5 commit c85aec0

File tree

2 files changed

+10
-14
lines changed

2 files changed

+10
-14
lines changed

_posts/2023-03-13-this-blog-is-now-a-pwa.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -35,13 +35,13 @@ If suddenly the device connects to the network it automatically reloads the page
3535

3636
---
3737

38-
I did hit this snag when using [`cache.addAll`] to cache my offline page. It does cache everything correctly. But when the user is offline and tries to navigate somewhere and the worker returns the offline page this error occurs:
38+
I did hit this snag when using [`cache.addAll`] to cache my offline page. It does cache everything correctly. But when the user is offline and tries to navigate somewhere and the worker returns the cached offline page this error occurs:
3939

4040
> The FetchEvent for "http://page-the-user-was-trying-to-access"
4141
> resulted in a network error response: a redirected response was
4242
> used for a request whose redirect mode is not "follow".
4343
44-
Apparently this is due to a [new security restriction] but I don't get it. It all seems so cryptic to me. [StackOverflow came to my rescue] though. So now I'm just calling `fetch` for each of the pages that I want to cache. All tutorials that I saw did use [`cache.addAll`] so either I'm doing something wrong or they're already out of date. If you bump into the same problem now you know!
44+
Apparently this is due to a [new security restriction] but I don't get it. It all seems so cryptic to me. [StackOverflow came to my rescue] though. So now I'm wrapping a `response` with `new Response(response.body)`. All tutorials that I saw simply used [`cache.addAll`] so either I'm doing something wrong or they're already out of date. If you bump into the same problem now you know!
4545

4646
---
4747

service-worker.js

+8-12
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
var CACHE_NAME = 'v1';
22

3-
async function cacheResources(resources) {
4-
var cache = await caches.open(CACHE_NAME);
5-
var promises = resources.map((resource) =>
6-
fetch(resource).then(response => cache.put(resource, response.clone()))
3+
function cacheInitialResources() {
4+
return caches.open(CACHE_NAME).then((cache) =>
5+
cache.addAll([
6+
'/',
7+
'/blog/',
8+
'/offline',
9+
]),
710
);
8-
return Promise.all(promises);
911
}
1012

1113
function clearOldCaches() {
@@ -50,13 +52,7 @@ async function fetchOrGoToOfflinePage(fetchEvent) {
5052

5153
function onInstall(installEvent) {
5254
skipWaiting();
53-
installEvent.waitUntil(
54-
cacheResources([
55-
'/',
56-
'/blog/',
57-
'/offline',
58-
])
59-
);
55+
installEvent.waitUntil(cacheInitialResources());
6056
}
6157

6258
function onActivate(activateEvent) {

0 commit comments

Comments
 (0)