fix: fix duplicated load bug of custom JS (#2771)

This commit is contained in:
DacongDA 2024-03-05 00:09:37 +08:00 committed by GitHub
parent 19942a8bd4
commit 11dbd5ba9a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -16,37 +16,32 @@ import {useEffect} from "react";
function CustomHead(props) { function CustomHead(props) {
useEffect(() => { useEffect(() => {
const suffix = new Date().getTime().toString(); if (!sessionStorage.getItem("customHead")) {
const suffix = new Date().getTime().toString();
if (!props.headerHtml) {return;} if (!props.headerHtml) {return;}
const node = document.createElement("div"); const node = document.createElement("div");
node.innerHTML = props.headerHtml; node.innerHTML = props.headerHtml;
node.childNodes.forEach(el => { node.childNodes.forEach(el => {
if (el.nodeName === "#text") { if (el.nodeName === "#text") {
return; return;
}
let innerNode = el;
innerNode.setAttribute("app-custom-head" + suffix, "");
if (innerNode.localName === "script") {
const scriptNode = document.createElement("script");
Array.from(innerNode.attributes).forEach(attr => {
scriptNode.setAttribute(attr.name, attr.value);
});
scriptNode.text = innerNode.textContent;
innerNode = scriptNode;
}
document.head.appendChild(innerNode);
});
return () => {
for (const el of document.head.children) {
if (el.getAttribute("app-custom-head" + suffix) !== null) {
document.head.removeChild(el);
} }
} let innerNode = el;
}; innerNode.setAttribute("app-custom-head" + suffix, "");
if (innerNode.localName === "script") {
const scriptNode = document.createElement("script");
Array.from(innerNode.attributes).forEach(attr => {
scriptNode.setAttribute(attr.name, attr.value);
});
scriptNode.text = innerNode.textContent;
innerNode = scriptNode;
}
document.head.appendChild(innerNode);
});
sessionStorage.setItem("customHead", "true");
}
}); });
} }