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& amp;铬:
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; } }
文件错了吗如果它们是正确的,那么在执行脚本之前,什么特定情况下成功回调会触发?
解决方法
从我可以看出来的来源,我同意你的结论,承诺应该始终在脚本执行后解决.
但是我的记忆告诉我,注意< script>有一些奇怪的事情.许多浏览器jQuery 1.x之一的标签支持(s | ed).问题浏览器在脚本在某个时间执行之前启动加载回调,否则我们不会在文档中添加一个注释.
我确信$.getScript的实现从那以后已经改变,文档中的问题行不再相关,无论我们需要在jQuery核心团队的前面提出问题.你真的应该在github上打开一个问题 – 随便cc @gnarf.