将回调添加到通过getScript从外部URL加载的函数

时间:2013-12-26 16:21:17

标签: javascript jquery

我正在通过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()函数。

此功能不受我控制,无回拨。

我可以为此功能添加回调吗?

1 个答案:

答案 0 :(得分:0)

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

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