Cache assets when cache is missing
This commit is contained in:
parent
bbeafab1ef
commit
8b8f6cbca2
1 changed files with 13 additions and 5 deletions
18
src/sw.js
18
src/sw.js
|
|
@ -96,14 +96,16 @@ const isEmoji = req => {
|
||||||
return url.pathname.startsWith('/emoji/')
|
return url.pathname.startsWith('/emoji/')
|
||||||
}
|
}
|
||||||
const isNotMedia = req => {
|
const isNotMedia = req => {
|
||||||
console.log('req.method=', req.method)
|
|
||||||
if (req.method !== 'GET') {
|
if (req.method !== 'GET') {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
const url = new URL(req.url)
|
const url = new URL(req.url)
|
||||||
console.log('pathname=', url.pathname)
|
|
||||||
return !url.pathname.startsWith('/media/')
|
return !url.pathname.startsWith('/media/')
|
||||||
}
|
}
|
||||||
|
const isAsset = req => {
|
||||||
|
const url = new URL(req.url)
|
||||||
|
return cacheFiles.includes(url.pathname)
|
||||||
|
}
|
||||||
|
|
||||||
const isSuccessful = (resp) => {
|
const isSuccessful = (resp) => {
|
||||||
if (!resp.ok) {
|
if (!resp.ok) {
|
||||||
|
|
@ -216,17 +218,23 @@ self.addEventListener('fetch', (event) => {
|
||||||
// Do not mess up with remote things
|
// Do not mess up with remote things
|
||||||
const isSameOrigin = (new URL(event.request.url)).origin === self.location.origin
|
const isSameOrigin = (new URL(event.request.url)).origin === self.location.origin
|
||||||
if (shouldCache && event.request.method === 'GET' && isSameOrigin && isNotMedia(event.request)) {
|
if (shouldCache && event.request.method === 'GET' && isSameOrigin && isNotMedia(event.request)) {
|
||||||
|
console.debug('[Service worker] fetch:', event.request.url)
|
||||||
event.respondWith((async () => {
|
event.respondWith((async () => {
|
||||||
const r = await caches.match(event.request)
|
const r = await caches.match(event.request)
|
||||||
|
const isEmojiReq = isEmoji(event.request)
|
||||||
|
|
||||||
if (r && (isSuccessful(r) || !isEmoji(event.request))) {
|
if (r && isSuccessful(r)) {
|
||||||
|
console.debug('[Service worker] already cached:', event.request.url)
|
||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(event.request)
|
const response = await fetch(event.request)
|
||||||
if (response.ok && isSuccessful(response) && isEmoji(event.request)) {
|
if (response.ok &&
|
||||||
const cache = await caches.open(emojiCacheKey)
|
isSuccessful(response) &&
|
||||||
|
(isEmojiReq || isAsset(event.request))) {
|
||||||
|
console.debug(`[Service worker] caching ${isEmojiReq ? 'emoji' : 'asset'}:`, event.request.url)
|
||||||
|
const cache = await caches.open(isEmojiReq ? emojiCacheKey : cacheKey)
|
||||||
await cache.put(event.request.clone(), response.clone())
|
await cache.put(event.request.clone(), response.clone())
|
||||||
}
|
}
|
||||||
return response
|
return response
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue