Skip to content
Advertisement

Running a script added after the page has loaded

I need to add the pages later for my project, but after adding the script tag at the bottom is not executed.

Main

const fetch = (url, call) => {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
         call(xhttp);
      }
  };
  xhttp.open("GET", url, true);
  xhttp.send();
}

const UpdatePage = page_name => {
  fetch(`/app/${page_name}`, (data => {
    App.innerHTML = data.responseText;
  }))
}

Code of new page

<div>
    <%= showId %>
</div>

<script>console.log("Welcome to somewhere")</script>

Page loads sucessfuly but the javascript not be executed. How i can execute the script tag on new page added?

Advertisement

Answer

I didn’t really understand your question. From what I did though you want to run the script after the page has loaded.

For that you can use the defer tag

<script src="script.js" defer></script>

Read this MDN article for more info.

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