【问题标题】:Adding a callback to a function that was loaded from an external URL via getScript向通过 getScript 从外部 URL 加载的函数添加回调
【发布时间】:2013-12-27 01:16:48
【问题描述】:

我正在通过 jQuery 的 getScript 方法加载一个 URL:

$.getScript(url, function () {      
    init(function() {
        console.log('test')
    });     
    // Can I add the above callback, so that, after the init has finished, I would see "test" in the console?
    elOverlay.show();
});

加载完 URL 后,我就可以访问 init() 函数了。

这个函数不受我控制,没有回调。

我可以给这个函数添加回调吗?

【问题讨论】:

  • 取决于init 的来源和作用。如果您提供更多代码,您可以拥有更多。
  • 除非函数接受回调或返回承诺,否则你就不走运了。我假设 init 函数是异步的,对,因为这是唯一需要这样做的原因?
  • 唯一的方法是通过 init 函数并找出异步部分并将回调推送到其中,除非 @Jason P 说过函数本身接受回调
  • 该函数确实接受回调 - 我无法编辑它 - 它属于我无法控制的另一个域 - 所以我不走运:)
  • @webmasters 一个不理想但可能是您能做的最好的选择是尝试找到表明init() 函数的东西(DOM 节点、一些数据等)已完成,然后设置setInterval 进行检查。

标签: javascript jquery


【解决方案1】:

一种可能的解决方案是创建包含主函数和回调的新函数。这是我的意思的例子:

function callbackInit(cb) {

    var status = false; // for extra assurance that the script is executed

    init(); // run the main function

    status = true;
    if(status) { 
      if(typeof callback === 'function') { // check if callback is function
          cb(); // then run the callback
      }
    }
}

【讨论】:

    猜你喜欢
    • 2010-10-16
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-27
    相关资源
    最近更新 更多