2012-03-18 37 views
0

我的主HTML文件在內容中動態加載;JQuery AJAX load()&ready()

<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操作何時結束? 如何解決?

感謝

+1

你必須首先包括jQuery庫... – 2012-03-18 15:05:44

回答

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

什麼,如果我有10個腳本? – fatbatman 2012-03-18 15:14:01

+0

另外如果可能的話,我想嘗試做到這一點,而不需要編輯remotePage.html,因爲該頁面本身可用並且結束目標。 – fatbatman 2012-03-18 15:20:02

+0

我已更新我的代碼。查看'3腳本'的答案。 '10腳本'類似。 – Engineer 2012-03-18 15:23:53