-
-
Save mantou132/52c2795604f7b1779cd66b2241650093 to your computer and use it in GitHub Desktop.
Service Worker Template - cache-else-network + network-else-cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const VERSION = '0.0.1'; | |
const assetsToCache = [...new Set([self.location.pathname, '/'])].map( | |
path => self.location.origin + path, | |
); | |
self.addEventListener('install', () => { | |
self.skipWaiting(); | |
self.caches.open(VERSION).then(cache => { | |
cache.addAll(assetsToCache); | |
}); | |
}); | |
self.addEventListener('fetch', event => { | |
const { request } = event; | |
const requestUrl = new URL(request.url); | |
const isSomeOrigin = requestUrl.origin === self.location.origin; | |
const fetchSuccess = response => { | |
if (response.ok) { | |
const responseCache = response.clone(); | |
self.caches | |
.open(VERSION) | |
.then(cache => cache.put(request, responseCache)); | |
return response; | |
} | |
throw new Error({ response }); | |
}; | |
const fetchError = ({ response }) => | |
response || | |
new Response( | |
` | |
<html> | |
<meta charset="utf-8"> | |
<meta http-equiv="refresh" content="3;url=${request.referrer}"> | |
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> | |
<title>Net Error</title> | |
<body> | |
<h1>Net Error</h1> | |
<p>Jumping to the previous page...</p> | |
<h1>网络错误</h1> | |
<p>正在跳转到前一页...</p> | |
</body> | |
</html> | |
`, | |
{ | |
status: 500, | |
statusText: 'Server Error', | |
headers: { | |
'Content-Type': 'text/html', | |
}, | |
}, | |
); | |
if (request.method !== 'GET') return; | |
event.respondWith( | |
fetch( | |
request, | |
isSomeOrigin ? {} : { mode: 'cors', credentials: 'same-origin' }, | |
) | |
.then(fetchSuccess) | |
.catch(error => | |
self.caches | |
.match(request, { | |
ignoreSearch: request.mode === 'navigate', | |
}) | |
.then(cache => { | |
if (cache !== undefined) { | |
return cache; | |
} | |
return fetchError(error); | |
}), | |
), | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment