JavaScript how to wait an other java script to be resolved first

I’m facing an issue with async java script. This is my html

<html>
   <head>
       <script src="/headScript.js"></script>
   </head>
  <body>
      <div id="inner_id" class="sample"> </div>
      ...
      <script src="/anOtherScript.js"></script>
  </body>
</html>

/headScript.js

  $(document).ready(function () {
  var target=$('#inner_id'); 
    $.ajax({                                                                 
        method: 'GET',
        url: '/example',
        success: function (result) {
                var el= document.createElement('span');
                el.id="new_element";              
                el.setAttribute('name', 'element');
                el.setAttribute('content', result);
                target.append(el)
        }
    });
  });

/anOtherScript.js

 $(document).ready(function () {
   console.log($('#new_element));
 });

the script from header create the new div but it seems that these two script are running asynchronously and at the console i get undefined. Is there any way that (anOtherScript) can wait the first one to be resolved first?

  • i cant change anything to html file
  • files that I’m able to make changes are the 2 scripts

31 thoughts on “JavaScript how to wait an other java script to be resolved first”

Leave a Comment