Skip to content

Commit

Permalink
Cache runtime resources on first load
Browse files Browse the repository at this point in the history
  • Loading branch information
microbit-robert committed Apr 26, 2024
1 parent e85920e commit 22dd200
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down

0 comments on commit 22dd200

Please sign in to comment.