From 22dd2007dcb00276df53edfec300d50a096dcf04 Mon Sep 17 00:00:00 2001 From: Robert Knight Date: Fri, 26 Apr 2024 13:50:47 +0100 Subject: [PATCH] Cache runtime resources on first load --- src/index.tsx | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/src/index.tsx b/src/index.tsx index e0501117c..d90693d3c 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -9,7 +9,35 @@ import App from "./App"; import reportWebVitals from "./reportWebVitals"; import { registerSW } from "virtual:pwa-register"; -registerSW({ immediate: true }); +registerSW({ + immediate: true, + // Cache runtime resources on first load. + // See https://github.com/GoogleChromeLabs/pwa-wp/issues/180. + onRegisteredSW(_, registration) { + if (registration) { + registration.onupdatefound = function () { + const installingWorker = registration?.installing; + if (installingWorker) { + installingWorker.onstatechange = function () { + if ( + installingWorker.state === "activated" && + navigator.serviceWorker.controller + ) { + const urlsToCache = [ + location.href, + ...performance.getEntriesByType("resource").map((r) => r.name), + ]; + installingWorker.postMessage({ + type: "CACHE_URLS", + payload: { urlsToCache }, + }); + } + }; + } + }; + } + }, +}); const root = createRoot(document.getElementById("root")!); root.render(