jQuery getScript加载与执行

Ben*_*Ben 12 jquery

getScript加入文档说的成功回调:

"一旦脚本加载但未必执行,则会触发回调."

但在我的测试中似乎并不属实.对于包含以下内容的主页:

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." );
});
Run Code Online (Sandbox Code Playgroud)

加载以下"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.");
Run Code Online (Sandbox Code Playgroud)

在FF和Chrome中产生相同的可预测控制台输出:

ajaxed script starting to execute.
elapsed time 5000 
ajaxed script finished executing.
success
Done callback executing now. 
Run Code Online (Sandbox Code Playgroud)

换句话说,在加载和执行加载的脚本之前,成功回调不会触发.这似乎是因为在jQuery 源代码中,globalEval函数立即调用脚本:

converters: {
    "text script": function( text ) {
        jQuery.globalEval( text );
        return text;
    }
}
Run Code Online (Sandbox Code Playgroud)

那些文档错了吗?如果它们是正确的,那么在脚本执行之前成功回调的具体情况是什么?

gna*_*arf 0

从我所看到的来源来看,我同意你的结论,即承诺应该在脚本执行始终得到解决。

<script>然而我的记忆告诉我,在 jQuery 1.x 支持的众多浏览器之一中注入标签有些奇怪(s|ed)。问题浏览器在脚本执行之前的某个时刻触发了加载的回调,否则我们不会在文档中添加有关它的注释。

我很确定从那时起, 的实现$.getScript已经发生了变化,并且文档中的问题行不再相关,无论哪种方式,我们都需要将问题摆在 jQuery 核心团队面前。你确实应该在github上提出一个问题- 请随时抄送@gnarf。