fix(loading): add error handling for main script

This commit is contained in:
Darren Yu 2025-11-12 14:54:50 +08:00
parent bb2f16bf5f
commit 2443dae72a
No known key found for this signature in database
GPG Key ID: 2D69AA5646405984
2 changed files with 27 additions and 0 deletions

View File

@ -112,6 +112,24 @@
});
observer.observe(appRoot, { childList: true });
});
async function handleLoadingError(event) {
try {
const resType = (await fetch(event.target.src)).headers.get("content-type") || "";
if (!resType.includes("javascript")) {
alert("A new version of the current page is available and ready to be refreshed.");
if ("caches" in window) {
const cacheNames = await caches.keys();
await Promise.all(cacheNames.map(cacheName => caches.delete(cacheName)));
}
if ("serviceWorker" in navigator) {
const registrations = await navigator.serviceWorker.getRegistrations();
await Promise.all(registrations.map(registration => registration.unregister()));
}
window.location.reload();
}
} catch (e) {}
}
</script>
</body>
{siteScript}

View File

@ -33,6 +33,15 @@ export default defineConfig({
},
],
}),
{
name: "load-js-error-handler",
transformIndexHtml(html) {
return html.replace(
/<script async type="module" crossorigin src="(.+?)"><\/script>/g,
`<script async type="module" crossorigin src="$1" onerror="handleLoadingError(event)"></script>`,
);
},
},
{
name: "load-stylesheet-async",
transformIndexHtml(html) {