当脚本完全加载并执行时 jquery .getscript() 回调
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14565365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery .getscript() callback when script is fully loaded and executed
提问by user2018232
As from the jquery api page http://api.jquery.com/jQuery.getScript/
从 jquery api 页面 http://api.jquery.com/jQuery.getScript/
Success Callback
The callback is fired once the script has been loaded but not necessarily executed.
$.getScript("test.js", function() { foo(); });
成功回调
一旦脚本加载但不一定执行,就会触发回调。
$.getScript("test.js", function() { foo(); });
if the foo()
function depend on test.js, it cannot be execute successfully.
如果foo()
函数依赖于 test.js,则无法成功执行。
I saw similar thing with google map api but in that case you can specify the callback function in the ajax script url. But in general is there an obvious way to wait until the ajax script executed to do the callback?
我在 google map api 中看到了类似的东西,但在这种情况下,您可以在 ajax 脚本 url 中指定回调函数。但总的来说,有没有一种明显的方法可以等到ajax脚本执行后再进行回调?
回答by Samuel Bergstr?m
I know it is an old question but i think both answers containing "done" are not explained by their owners and they are in fact the best answers.
我知道这是一个老问题,但我认为包含“完成”的两个答案都没有由其所有者解释,实际上它们是最好的答案。
The most up-voted answer calls for using "async:false" which will in turn create a sync call which is not optimal. on the other hand promises and promise handlers were introduced to jquery since version 1.5 (maybe earlier?) in this case we are trying to load a script asynchronously and wait for it to finish running.
投票最多的答案要求使用“async:false”,这反过来会创建一个不是最佳的同步调用。另一方面,自 1.5 版(可能更早?)以来,jquery 引入了 promise 和 promise 处理程序,在这种情况下,我们尝试异步加载脚本并等待它完成运行。
The callback by definition getScript documentation
回调定义getScript 文档
The callback is fired once the script has been loaded but not necessarily executed.
一旦脚本加载但不一定执行,就会触发回调。
what you need to look for instead is how promises act. In this case as you are looking for a script to load asynchronously you can use either "then" or "done" have a look at this threadwhich explains the difference nicely.
相反,您需要寻找的是 Promise 的行为方式。在这种情况下,当您正在寻找异步加载的脚本时,您可以使用“then”或“done”查看此线程,它很好地解释了差异。
Basically done will be called only when a promise is resolved. in our case when the script was loaded successfully and finished running. So basically in your code it would mean:
基本上 done 只会在承诺被解决时才会被调用。在我们的例子中,脚本成功加载并完成运行。所以基本上在你的代码中它意味着:
$.getScript("test.js", function() {
foo();
});
should be changed to:
应改为:
$.getScript("test.js").done(function(script, textStatus) {
console.log("finished loading and running test.js. with a status of" + textStatus);
});
回答by Akash
$.getScript(...)
+ setInterval(...)
worked for me:
$.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....
}
Once the variable
we are looking for is defined (in my case window.grecaptcha
, i can call a closure function
which can be abstracted out
.
一旦variable
定义了我们正在寻找的(在我的情况下window.grecaptcha
,我可以调用 a closure function
which can be abstracted out
.
Good Luck...
祝你好运...
回答by DadViegas
You can use ajax
你可以使用 ajax
jQuery.ajax({
async:false,
type:'GET',
url:script,
data:null,
success:callback,
dataType:'script'
});
Async is false, because you want to load and execute the script, after that in success callback you can call your function foo()
异步是假的,因为你想加载和执行脚本,然后在成功回调之后你可以调用你的函数 foo()
回答by amee9451
$.getScript( "ajaxFile/myjs.js" )
.done(function( s, Status ) {
console.warn( Status );
})
.fail(function( jqxhr, settings, exception ) {
console.warn( "Something went wrong"+exception );
});
回答by Corey Alix
I'm afraid the solution requires polling for the dependency. Alternatively the script needs to be wrapped in a pre-defined callback like AMD.
恐怕解决方案需要对依赖项进行轮询。或者,脚本需要包含在预定义的回调中,如 AMD。
回答by BrunoRB
I was facing the same issue today and came up with a solution based on promises and a interval timer:
我今天面临同样的问题,并提出了一个基于承诺和间隔计时器的解决方案:
$.getScript("test.js", function() {
var $def = $.Deferred();
if (typeof foo === 'undefined') { // "foo" isn't available
var attempts = 0;
// create an interval
// that will check each 100ms if the "foo" function
// was loaded
var interval = setInterval(function() {
if (typeof foo !== 'undefined') { // loaded
window.clearInterval(interval);
$def.resolve();
}
// after X unsuccessfull attempts, abort the operation
else if (attempts >= 100) {
window.clearInterval(interval);
$def.reject('Something went wrong');
}
attempts++;
}, 100);
}
else { // "foo" is available
$def.resolve();
}
return $def.promise();
}).then(function() {
// at this point "foo()" is definitely available.
}).fail(function() {
// deal with the failure
});
The ideia is that you load a given script that will expose some variable (the foo
function in your question example) that still doesn't exist, so after the script is loaded by getScript
you check if this variable exists, if not you create an interval that will continuously check if the variable is available, and only when this condition is satisfied you resolve the promise.
想法是您加载一个给定的脚本,该脚本将公开一些foo
仍然不存在的变量(问题示例中的函数),因此在getScript
您加载脚本后检查该变量是否存在,如果不存在,则创建一个间隔将不断检查变量是否可用,并且只有在满足此条件时才能解决承诺。
回答by kathir
$getScript use like this
$getScript 像这样使用
$.getScript( "js/jquery.raty.min.js" )
.done(function( script, textStatus ) {
console.log( textStatus );
}
});
this is working fine for me
这对我来说很好用