Prevent double-loading of afterDOMReady scripts (#2213)
Some checks failed
Build and Test / build-and-test (ubuntu-latest) (push) Has been skipped
Build and Test / publish-tag (push) Has been skipped
Build and Test / build-and-test (windows-latest) (push) Has been cancelled
Build and Test / build-and-test (macos-latest) (push) Has been cancelled

Co-authored-by: Adam <adam@canny.io>
This commit is contained in:
Adam Laycock
2025-11-27 15:51:56 -07:00
committed by GitHub
parent c99c8070f2
commit 87f7f4804e
3 changed files with 7 additions and 6 deletions

View File

@@ -294,7 +294,7 @@ export function renderPage(
</body>
{pageResources.js
.filter((resource) => resource.loadTime === "afterDOMReady")
.map((res) => JSResourceToScriptElement(res))}
.map((res) => JSResourceToScriptElement(res, true))}
</html>
)

View File

@@ -115,9 +115,9 @@ async function _navigate(url: URL, isBack: boolean = false) {
}
// now, patch head, re-executing scripts
const elementsToRemove = document.head.querySelectorAll(":not([spa-preserve])")
const elementsToRemove = document.head.querySelectorAll(":not([data-persist])")
elementsToRemove.forEach((el) => el.remove())
const elementsToAdd = html.head.querySelectorAll(":not([spa-preserve])")
const elementsToAdd = html.head.querySelectorAll(":not([data-persist])")
elementsToAdd.forEach((el) => document.head.appendChild(el))
// delay setting the url until now

View File

@@ -26,9 +26,10 @@ export type CSSResource = {
export function JSResourceToScriptElement(resource: JSResource, preserve?: boolean): JSX.Element {
const scriptType = resource.moduleType ?? "application/javascript"
const spaPreserve = preserve ?? resource.spaPreserve
if (resource.contentType === "external") {
return (
<script key={resource.src} src={resource.src} type={scriptType} spa-preserve={spaPreserve} />
<script key={resource.src} src={resource.src} type={scriptType} data-persist={spaPreserve} />
)
} else {
const content = resource.script
@@ -36,7 +37,7 @@ export function JSResourceToScriptElement(resource: JSResource, preserve?: boole
<script
key={randomUUID()}
type={scriptType}
spa-preserve={spaPreserve}
data-persist={spaPreserve}
dangerouslySetInnerHTML={{ __html: content }}
></script>
)
@@ -54,7 +55,7 @@ export function CSSResourceToStyleElement(resource: CSSResource, preserve?: bool
href={resource.content}
rel="stylesheet"
type="text/css"
spa-preserve={spaPreserve}
data-persist={spaPreserve}
/>
)
}