脚本完全加载并执行时,jquery .getscript()回调

问题描述 投票:37回答:7

从jquery api页面http://api.jquery.com/jQuery.getScript/

成功回调

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

$.getScript("test.js", function() {
    foo();
});

如果foo()函数依赖于test.js,则无法成功执行。

我在google map api中看到了类似的东西,但在这种情况下你可以在ajax脚本url中指定回调函数。但总的来说有一种明显的方法可以等到执行ajax脚本来执行回调吗?

jquery ajax
7个回答
11
投票

我知道这是一个古老的问题,但我认为包含“完成”的两个答案都没有被其所有者解释,事实上它们是最好的答案。

最高投票的答案要求使用“async:false”,这反过来会创建一个不是最佳的同步调用。另一方面,承诺和承诺处理程序从1.5版本开始引入jquery(可能更早?)在这种情况下,我们试图异步加载脚本并等待它完成运行。

根据定义getScript documentation的回调

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

你需要寻找的是承诺如何行事。在这种情况下,当您正在寻找一个异步加载的脚本时,您可以使用“then”或“done”来查看this thread,它可以很好地解释差异。

只有在解决了承诺时才会调用基本上完成的操作。在我们的情况下,脚本成功加载并完成运行。所以基本上在你的代码中它意味着:

$.getScript("test.js", function() {
    foo();
});

应改为:

$.getScript("test.js").done(function(script, textStatus) {
    console.log("finished loading and running test.js. with a status of" + textStatus);
});

3
投票

你可以使用ajax

jQuery.ajax({
        async:false,
        type:'GET',
        url:script,
        data:null,
        success:callback,
        dataType:'script'
    });

Async是假的,因为你想加载并执行脚本,之后成功回调你可以调用你的函数foo()


3
投票

$.getScript(...) + setInterval(...) worked for me:

$.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....
  }

一旦我们正在寻找的variable被定义(在我的情况下window.grecaptcha,我可以称为closure function,可以是abstracted out

祝好运...


2
投票
$.getScript( "ajaxFile/myjs.js" )
.done(function( s, Status ) {
    console.warn( Status );
})
.fail(function( jqxhr, settings, exception ) {
    console.warn( "Something went wrong"+exception );
});

0
投票

我担心解决方案需要轮询依赖项。或者,脚本需要包含在像AMD这样的预定义回调中。


0
投票

我今天面临同样的问题,并提出了一个基于promises和间隔计时器的解决方案:

$.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
});

ideia是你加载一个给定的脚本,它会暴露一些仍然不存在的变量(你的问题例子中的foo函数),所以在getScript加载脚本之后你检查这个变量是否存在,如果没有你创建一个将持续检查变量是否可用的间隔,并且仅当满足此条件时才解析承诺。


-1
投票

$ getScript像这样使用

$.getScript( "js/jquery.raty.min.js" )
    .done(function( script, textStatus ) {
          console.log( textStatus );
         }
          });

这对我来说很好

© www.soinside.com 2019 - 2024. All rights reserved.