Home > database >  Running a script added after the page has loaded
Running a script added after the page has loaded

Time:07-11

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?

CodePudding user response:

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.

CodePudding user response:

You must call the function

fetch();
UpdatePage();

Before doing this, you must call your file js in the ejs file

  • Related