Question

My main HTML file dynamically loads in content with;

<html>
<head>
  <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
</head>
<body>
  Loading please wait
  <script type="text/javascript">
    $(document).ready(function(){
      $('body').load("remotePage.html");
    });
  </script>
</body>
</html>

remotePage.html is;

<html>
<head>
  <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
  <script type="text/javascript" src="script1.js"></script>
  <script type="text/javascript" src="script2.js"></script>
  <script type="text/javascript" src="script3.js"></script>
</head>
<body>
<script type="text/javascript">

  function init(){
    someFunctionThatDependsOnAllScripts();   //Fails because all scripts is not yet loaded
  }

  $(document).ready(init);

<script>
</body>
</html>

It fails because the ready in script1.js is called before script1.js is loaded. Having a callback on load doesn't seem to help.

$(function(){
  $('body').load("remotePage.html", function(){
    init();  //doesn't work either
  });
});

How can I tell when all ajax operations for loading in resources required by remotePage.html having finished? How to fix?

Thanks

Was it helpful?

Solution

Change script tag to this:

<script type="text/javascript" src="script1.js" onload="init()"></script>

And remove $(init); method from your script.

UPDATED: If you had multiple scripts to include then you can use something like this:

<html>
<head>
  <script type="text/javascript" src="script1.js" onload="scriptLoaded()"></script>
  <script type="text/javascript" src="script2.js" onload="scriptLoaded()"></script>
  <script type="text/javascript" src="script3.js" onload="scriptLoaded()"></script>
</head>
<body>
<script type="text/javascript">
   //
   var totalScriptsToLoad = 3;
   function scriptLoaded(){
        if(--totalScriptsToLoad == 0){
             init();
        }
   }
   //
   function init(){
       someFunctionFromScript1();   //Fails because script1 is not yet loaded
   }

<script>
</body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top