Fix the response stream of service worker
After service worker update (rebuild the site), the following error will occasionally appear: ``` The FetchEvent for "<url_from_CDN>" resulted in a network error response: an "opaque" response was used for a request whose type is not no-cors ``` This commit ensures that the response object has been cached before being returned.
This commit is contained in:
parent
efd8d44b12
commit
e84331b26a
1 changed files with 29 additions and 18 deletions
37
sw.js
37
sw.js
|
@ -36,25 +36,36 @@ self.addEventListener('install', e => {
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
self.addEventListener('fetch', e => {
|
self.addEventListener('fetch', event => {
|
||||||
e.respondWith(
|
event.respondWith(
|
||||||
caches.match(e.request).then(r => {
|
caches.match(event.request)
|
||||||
/* console.log(`[sw] method: ${e.request.method}, fetching: ${e.request.url}`); */
|
.then(response => {
|
||||||
return r || fetch(e.request).then(response => {
|
if (response) {
|
||||||
const url = e.request.url;
|
|
||||||
|
|
||||||
if (e.request.method !== 'GET'
|
|
||||||
|| !verifyDomain(url)
|
|
||||||
|| isExcluded(url)) {
|
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
return caches.open(cacheName).then(cache => {
|
return fetch(event.request)
|
||||||
/* console.log('[sw] Caching new resource: ' + e.request.url); */
|
.then(response => {
|
||||||
cache.put(e.request, response.clone());
|
const url = event.request.url;
|
||||||
|
|
||||||
|
if (event.request.method !== 'GET' ||
|
||||||
|
!verifyDomain(url) ||
|
||||||
|
isExcluded(url)) {
|
||||||
return response;
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
see: <https://developers.google.com/web/fundamentals/primers/service-workers#cache_and_return_requests>
|
||||||
|
*/
|
||||||
|
let responseToCache = response.clone();
|
||||||
|
|
||||||
|
caches.open(cacheName)
|
||||||
|
.then(cache => {
|
||||||
|
/* console.log('[sw] Caching new resource: ' + event.request.url); */
|
||||||
|
cache.put(event.request, responseToCache);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
return response;
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
Loading…
Reference in a new issue