cache static assets
This commit is contained in:
parent
7ca242fff4
commit
8c0a6ccf7f
32
app/service-worker/cache-utils.ts
Normal file
32
app/service-worker/cache-utils.ts
Normal 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;
|
||||||
|
}
|
@ -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);
|
||||||
|
Loading…
Reference in New Issue
Block a user