【发布时间】:2014-02-07 09:59:15
【问题描述】:
getScript docs 表示成功回调:
“一旦脚本被加载但不一定执行,回调就会被触发。”
但在我的测试中,这似乎不是真的。对于具有以下内容的主机页面:
var startTime = new Date();
$.getScript("test.js")
.done(function( script, textStatus ) {
console.log( textStatus );
console.log( "Done callback executing now.")
})
.fail(function( jqxhr, settings, exception ) {
console.log("error." );
});
加载以下“test.js”脚本,它将 UI 绑定 5 秒:
console.log("ajaxed script starting to execute.");
var newTime = new Date();
while (newTime - startTime < 5000) {
newTime = new Date();
}
console.log("elapsed time", newTime - startTime);
console.log("ajaxed script finished executing.");
在 FF 和 Chrome 中产生相同的可预测控制台输出:
ajaxed script starting to execute.
elapsed time 5000
ajaxed script finished executing.
success
Done callback executing now.
换句话说,在加载的脚本加载并执行之前,成功回调永远不会触发。这似乎是因为在 jQuery source 中,globalEval 函数正在立即调用脚本:
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
那么文档错了吗?如果它们是正确的,那么在什么特定情况下成功回调会在脚本执行之前触发?
【问题讨论】:
-
您可以将您的问题和降价提交给github.com/jquery/api.jquery.com/issues 吗? :)
-
文档肯定是错误的,谢谢提醒:)
-
谢谢,提交的 github 问题:github.com/jquery/api.jquery.com/issues/420
-
对于它的价值:我的一个应用程序正好遭受这种竞争条件。外部脚本除了设置一个全局变量什么都不做,几乎总是在回调之前执行。但是偶尔它不会,并且当回调运行时全局变量仍然是
undefined,导致应用程序崩溃。我想知道是否有一种可靠的方法可以延迟回调的执行,直到脚本执行完毕......
标签: jquery