0

During the process of developing a website, I made a navigation bar in a separate HTML file (nav.html), that i can load into any page I want use AJAX calls in Javascript. The problem is that the script contained in this navbar doesn't run when the navbar is loaded in the actual page. (The navbar however is loaded correctly in the page)

nav.html

<div id= topnav class="topnav">
  <...html...>
</div>

<script>
    console.log("THIS WON'T GET PRINTED OUT")
</script>

page.html

<html>
   <nav id="nav"></nav>
</html>

<script>
loadTopBar()
function loadTopBar(){
    var xhr= new XMLHttpRequest();
    xhr.open('GET', 'static/getnavbar', true);
    xhr.onreadystatechange= function() {
        if (this.readyState!==4) return;
        if (this.status!==200) return; // or whatever error handling you want
        
        document.getElementById('nav').innerHTML= this.responseText;
    };
    xhr.send();
}
</script>
  • 1
    Enclose any code you want to be able to call in a function and upon the successful loading of the AJAX result, call that function. – Scott Marcus Mar 29 '21 at 19:11

1 Answers1

0

Enclose any code you want to be able to call in a function and upon the successful loading of the AJAX result, call that function.

Also, instead of checking the readystate and status and returning when they aren't what you want, just continue when they are.

nav.html

<div id= topnav class="topnav">
  <...html...>
</div>

<script>
    // Code that is not inside of a function should be avoided so that
    // you can more precisely control when and how often it executes.
    function foo(){
      console.log("THIS WON'T GET PRINTED OUT");
    }
</script>

page.html

<html>
   <nav id="nav"></nav>
</html>

<script>
loadTopBar()
function loadTopBar(){
    var xhr= new XMLHttpRequest();
    xhr.open('GET', 'static/getnavbar', true);
    xhr.onreadystatechange= function() {

        if (this.readyState===4 && this.status ===200){     
          document.getElementById('nav').innerHTML= this.responseText;

          foo();  // <-- Call the function that should now be available
        }
    };
    xhr.send();
}
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71