我制作了一个场景很少的游戏。每个场景都有自己的 javascript,我想异步加载它,然后将特定的场景文件加载到 div 中。
这是我的 html 索引.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');脚本加载成功完成后立即执行。
我怎样才能做到这一点?
最佳答案
只需将另一个 .load()
放入另一个 .load()
函数的回调
$( "#targetelement" ).load('myajaxpage.php', function(){
//call back
$( "#targetelement" ).load('myajaxpage.html', function(){
//call back
})
});
因为我意识到您的问题标题与您所问的内容不同
I want the second command: $( "#test" ).load('div.html'); to be executed straight after the scripts loading finished successfully.
您需要使用具有回调
功能的脚本加载器,例如下面的脚本加载器
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
});
yepnope.injectJs("jquery.js", function () {
// your function you want to call after the scripts above is loaded
}, {
charset: "utf-8"
}, 5000);
嗯,有很多script loaders但根据我的经验,以上两个对我来说真的很有好处
关于javascript - 如何在另一个函数完成后执行.load函数?请参阅示例中的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16364965/