jQuery getScript加载与执行 [英] jQuery getScript load vs execution

查看:110
本文介绍了jQuery getScript加载与执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

getScript文档说到以下成功回调:

一旦脚本已加载但不一定执行,就会触发回调."

"The callback is fired once the script has been loaded but not necessarily executed."

但是在我的测试中,似乎并非如此.对于具有以下内容的主机页面:

But in my testing that doesn't seem to be true. For a host page with:

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秒钟:

loading the following "test.js" script which ties up the UI for 5 seconds:

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; amp;中产生相同的可预测控制台输出Chrome:

results in the same predictable console output in both FF & Chrome:

ajaxed script starting to execute.
elapsed time 5000 
ajaxed script finished executing.
success
Done callback executing now. 

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

In other words, the success callback does not ever fire until the loaded script is both loaded and executed. This seems to be because in the jQuery source, the globalEval function is calling the script immediately:

converters: {
    "text script": function( text ) {
        jQuery.globalEval( text );
        return text;
    }
}

那么文档有误吗?如果它们是正确的,那么在什么特定情况下将在脚本执行之前在 处触发成功回调?

So are the docs wrong? If they are correct, then in what specific cases will the success callback fire before the script is executed?

推荐答案

我在1.7.1版本的jQuery中遇到了这个问题.在版本2.1.0之前,前述的$.globalEval()函数是使用臭名昭著的eval()的间接调用在全局环境中运行代码.

I have ran into this issue in 1.7.1 version of jQuery. Before version 2.1.0 the forementioned $.globalEval() function was using indirect call of infamous eval() to run code in global environment.

因此,以前肯定是一个问题.

So it certainly was an issue before.

在版本2.1.0中,由于某些缺少间接eval调用的原因,他们已切换到脚本插入.如果愿意,可以在这里找到更多信息.

In version 2.1.0 they have switched to script insertion because of certain lacks in indirect eval call. You can find more info here if you like.

http://perfectionkills.com/global-eval-what-are -the-options/

在具有脚本插入功能的较新实现中,此行很神奇

In newer implementation with script insertion this line is doing the magic

context.head.appendChild( script ).parentNode.removeChild( script );

除非存在某种奇怪的底层浏览器机制,否则似乎在从DOM树中删除脚本之前必须立即执行脚本 .

Unless there is some strange underlying browser mechanism it seems script must be executed immediately, before being removed from DOM tree.

这篇关于jQuery getScript加载与执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆