来自jquery api页面 http://api.jquery.com/jQuery.getScript/
成功回调
一旦脚本加载但未必执行,则会触发回调.
Run Code Online (Sandbox Code Playgroud)$.getScript("test.js", function() { foo(); });
如果foo()函数依赖于test.js,则无法成功执行.
我在google map api中看到了类似的东西,但在这种情况下你可以在ajax脚本url中指定回调函数.但总的来说有一种明显的方法可以等到执行ajax脚本来执行回调吗?
小智 12
我知道这是一个古老的问题,但我认为包含"完成"的两个答案都没有被其所有者解释,事实上它们是最好的答案.
最高投票的答案要求使用"async:false",这反过来会创建一个不是最佳的同步调用.另一方面,承诺和承诺处理程序从1.5版本开始引入jquery(可能更早?)在这种情况下,我们试图异步加载脚本并等待它完成运行.
根据定义getScript文档的回调
一旦脚本加载但未必执行,则会触发回调.
你需要寻找的是承诺如何行事.在这种情况下,当您正在寻找异步加载的脚本时,您可以使用"then"或"done"查看此线程,这很好地解释了差异.
只有在解决了承诺时才会调用基本上完成的操作.在我们的情况下,脚本成功加载并完成运行.所以基本上在你的代码中它意味着:
$.getScript("test.js", function() {
foo();
});
Run Code Online (Sandbox Code Playgroud)
应改为:
$.getScript("test.js").done(function(script, textStatus) {
console.log("finished loading and running test.js. with a status of" + textStatus);
});
Run Code Online (Sandbox Code Playgroud)
$.getScript(...)+setInterval(...)为我工作:$.getScript('https://www.google.com/recaptcha/api.js')
.done(function() {
var setIntervalID = setInterval(function() {
if (window.grecaptcha) {
clearInterval(setIntervalID);
console.log(window.grecaptcha);
letsWorkWithWindowDotGreptcha();
};
}, 300);
});
function letsWorkWithWindowDotGreptcha() {
// window.greptcha is available here....
}
Run Code Online (Sandbox Code Playgroud)
一旦variable定义了我们正在寻找的(在我的情况下window.grecaptcha,我可以调用 a closure functionwhich can be abstracted out.
祝你好运...
你可以使用ajax
jQuery.ajax({
async:false,
type:'GET',
url:script,
data:null,
success:callback,
dataType:'script'
});
Run Code Online (Sandbox Code Playgroud)
Async 为 false,因为您想要加载并执行脚本,之后在成功回调中您可以调用您的函数 foo()
| 归档时间: |
|
| 查看次数: |
30367 次 |
| 最近记录: |