2013-05-03 43 views
0

我製作的遊戲只有很少的場景。每個場景都有它自己的JavaScript,我想異步加載,之後將特定的場景文件加載到div中。如何在另一個函數完成後執行.load函數?請參閱示例中的函數

這裏是我的html 的index.html

<!DOCTYPE html> 
<html> 
<head> 
    <title></title> 
    <script src="http://code.jquery.com/jquery-1.9.1.js"> </script> 

    <script type="text/javascript" src="first.js" id="first" ></script> 
</head> 
<body> 

<div id="test" style="width: 800px; height: 400px; background: black"> 
    hello 

</div> 
            <button id="submit">submit</button> 

</body> 
</html> 

下面是兩個工作功能。

第一個

$(document).ready(function() { 

    $('#submit').click(function() { 


     (function() { 
      var myscript = document.createElement('script'); 
      myscript.type = 'text/javascript'; 
      myscript.src = ('second.js'); 
      var s = document.getElementById('first'); 
      s.parentNode.insertBefore(myscript, s); 
     })(); 

    }); 

}); 

這裏是第二

$("#test").load('div.html'); 

我想第二個命令:$( 「#TEST」).load( 'div.html');在腳本加載成功完成後立即執行。

我該怎麼做?

回答

2

只是把另一​​到回調的另一個​​功能

$("#targetelement").load('myajaxpage.php', function(){ 
     //call back 
     $("#targetelement").load('myajaxpage.html', function(){ 
      //call back 
     }) 
}); 

的,因爲我意識到你的問題的標題是這是你問

我想不同第二個命令:$(「#test」).load('div.html');在腳本加載成功完成後直接執行 執行

您需要使用具有callback功能,例如下面的腳本裝載機下面

http://headjs.com/

head.js("/path/to/jquery.js", "/google/analytics.js", "/js/site.js", function() { 

    // your function you want to call after the scripts above is loaded 

}); 

http://yepnopejs.com/

yepnope.injectJs("jquery.js", function() { 
    // your function you want to call after the scripts above is loaded 

}, { 
    charset: "utf-8" 
}, 5000); 

腳本加載以及有很多的script loaders但在我的經驗上面的兩個對我來說真的很好

+0

這不是我的問題的答案 – 2013-05-03 18:05:28

+0

剛剛爲您更新了答案 – 2013-05-03 18:15:12

+0

其實我想爲scene1加載一些腳本,並且在我去scene2之後我想將這些腳本替換爲其他腳本。所以我必須給他們一個id或什麼(爲了替換他們) 所以我更喜歡使用我寫的功能。或者它是否有能力用head.js替換腳本? – 2013-05-03 18:23:10

相關問題