0

我的主要 HTML 文件动态加载内容;

<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 是;

<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>

它失败是因为在 script1.js 加载之前调用了 script1.js 中的 ready。加载回调似乎没有帮助。

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

如何判断所有用于加载 remotePage.html 所需资源的 ajax 操作何时完成?怎么修?

谢谢

4

1 回答 1

0

将脚本标记更改为:

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

$(init);并从您的脚本中删除 方法。

更新:如果您要包含多个脚本,那么您可以使用以下内容:

<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>
于 2012-03-18T15:08:15.733 回答