Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 21 additions & 3 deletions documentation/docs/30-advanced/40-service-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,21 +66,39 @@ self.addEventListener('fetch', (event) => {

// `build`/`files` can always be served from the cache
if (ASSETS.includes(url.pathname)) {
return cache.match(url.pathname);
const response = await cache.match(url.pathname);

if (response) {
return response;
}
}

// for everything else, try the network first, but
// fall back to the cache if we're offline
try {
const response = await fetch(event.request);

// if we're offline, fetch can return a value that is not a Response
// instead of throwing - and we can't pass this non-Response to respondWith
if (!(response instanceof Response)) {
throw new Error('invalid response from fetch');
}

if (response.status === 200) {
cache.put(event.request, response.clone());
}

return response;
} catch {
return cache.match(event.request);
} catch (err) {
const response = await cache.match(event.request);

if (response) {
return response;
}

// if there's no cache, then just error out
// as there is nothing we can do to respond to this request
throw err;
}
}

Expand Down