I made a script that takes the text of a html file and inserts it into another html file; I did this so I don’t need to update my header and sidebar on every page if I make a change. the script works to insert the html but some scripts from the file are not run once inserted into the main html.
function includeHTML() {
let elements = document.querySelectorAll("[include-html]");
for (let i = 0; i < elements.length; i++) {
const elem = elements[i];
let file = elem.getAttribute("include-html");
fetch(file).then(response => response.text()).then(data => {
elem.innerHTML = data; // inject html
let scripts = elem.querySelectorAll("script");
for (let i = 0; i < scripts.length; i++) { // find scripts
let script = scripts[i];
let newScript = document.createElement("script");
let attrs = script.attributes;
for (let i = 0; i < attrs.length; i++) { // copy attributes
attr = attrs[i];
newScript.setAttribute(attr.name, attr.value);
};
newScript.innerHTML = script.innerHTML // copy internal script
script.replaceWith(newScript); // replace script
};
});
elem.removeAttribute("include-html");
};
};
includeHTML();
^ this is my script, after inserting to innerHTML it replaces the scripts, this make some work but not others
<html>
<head>
<script defer src="/include.js"></script>
</head>
<body>
<div include-html="/file.html"></div>
</body>
</html>
^ and this is an example of how I would use it
if the script inserted uses DOMContentLoaded I guess it is inserted after it’s already fired so it isn’t executed, one solution I found is to fire DOMContentLoaded manually after a second but I feel like this could be dependent on the users computer/internet speed, and it would make any scripts elsewhere on the page run twice if they catch the first firing so surely this is not the best way of doing it
by the way I am hosting on neocities so I dont have any backend access, thank you in advance for any help