cache static assets

This commit is contained in:
m5r 2022-06-04 15:48:37 +02:00
parent 7ca242fff4
commit 8c0a6ccf7f
2 changed files with 39 additions and 4 deletions

View File

@ -0,0 +1,32 @@
import type { FetchEventWithPreloadResponse } from "./fetch";
export const ASSET_CACHE = "asset-cache";
export async function cacheAsset(event: FetchEventWithPreloadResponse) {
const url = new URL(event.request.url);
const cachedResponse = await caches.match(event.request, {
cacheName: ASSET_CACHE,
ignoreVary: true,
ignoreSearch: true,
});
console.debug(`Serving asset from ${cachedResponse ? "cache" : " network"}`, url.pathname);
const fetchPromise = (async () => {
const cache = await caches.open(ASSET_CACHE);
const preloadedResponse = await event.preloadResponse;
const response = preloadedResponse || (await fetch(event.request));
switch (response.status) {
case 200:
cache.put(event.request, response.clone());
break;
case 404:
cache.delete(event.request);
break;
}
return response;
})();
return cachedResponse || fetchPromise;
}

View File

@ -1,9 +1,12 @@
import { ASSET_CACHE, cacheAsset } from "~/service-worker/cache-utils";
declare let self: ServiceWorkerGlobalScope; declare let self: ServiceWorkerGlobalScope;
export default async function handleFetch(event: FetchEvent & { preloadResponse?: Promise<Response | undefined> }) { export type FetchEventWithPreloadResponse = FetchEvent & { preloadResponse?: Promise<Response | undefined> };
const preloaded = await event.preloadResponse;
if (preloaded) { export default async function handleFetch(event: FetchEventWithPreloadResponse) {
return preloaded; if (["font", "image", "script", "style"].includes(event.request.destination)) {
return cacheAsset(event);
} }
return fetch(event.request); return fetch(event.request);