Skip to content
Advertisement

Possible to execute script when loading local html file?

I am clicking on a link and loading in an html file which consist of:

<div id="galleryPage">
    <p>Hello2</p>
</div>

<script type="text/javascript">
    console.log("hellosdsd");
</script>

I then add this into a div on my page and it looks like:

enter image description here

the script never executes…

What am I missing?

Loading the html like this:

document.querySelectorAll(".link").forEach((item) => {
    item.addEventListener("click", (event) => {
        event.preventDefault();
        const url = event.target.dataset["url"];

        get_html_file(`./Pages/${url}/`, (data) => {
            document.getElementById("container").innerHTML = data;
        });

        return false;
    });
});

function get_html_file(path, success, errorCallback) {
    fetch(path)
        .then((response) => {
            if (!response.ok) {
                throw new Error("Network response was not ok");
            }
            return response.text();
        })
        .then((data) => {
            if (success) success(data);
            // document.getElementById("container").innerHTML = data;
        })
        .catch((error) => {
            if (errorCallback) errorCallback(error);
            console.error(
                "There has been a problem with your fetch operation:",
                error
            );
        });
}

Advertisement

Answer

Yep, modifying innerHTML won’t evaluate the script tags it inserts.

You might want to do something like

[...document.querySelectorAll("#container script")].forEach(script => {
  if(script.dataset.evaluated) return;  // If already evaluated, skip
  eval(script.innerText);
  script.dataset.evaluated = 1;  // Mark as evaluated
});

after you load in the new HTML.

You could also do e.g. script.parentNode.removeChild(script) instead of the dataset trick, but this is more useful for debugging.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement