【问题标题】:JQuery AJAX load() & ready()JQuery AJAX load() & ready()
【发布时间】:2012-03-18 15:04:40
【问题描述】:

我的主 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 中的 ready 在 script1.js 加载之前被调用。 加载回调似乎没有帮助。

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

我如何知道用于加载 remotePage.html 所需资源的所有 ajax 操作何时完成? 如何解决?

谢谢

【问题讨论】:

  • 你必须先包含 jQuery 库..

标签: jquery ajax jquery-load ready


【解决方案1】:

把脚本标签改成这样:

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

【讨论】:

  • 如果我有 10 个脚本呢?
  • 另外,如果可能的话,我想尝试在不编辑 remotePage.html 的情况下执行此操作,因为该页面本身和最终目标都是可用的。
  • 我已经更新了我的代码。请参阅“3 个脚本”的答案。 “10 个脚本”类似。
  • 那行得通,我需要编辑 remotePage.html 但我可以忍受,你肯定回答了我的问题,谢谢 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-16
  • 2012-01-13
  • 1970-01-01
  • 2011-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多