I need generic javascript "wait for a function to be available"

I found this great snippet. Make my account text wait for other scripts to load , which shows me how to wait for the function to be available before calling it.

I currently have this local code in my script that I created together that works for me

waitForFnc();

function waitForFnc() {
    if (typeof Portal.Management_Init == "undefined") {
        window.setTimeout(waitForFnc, 50);
    }
    else {
        Portal.Management_Init();
    }
}

However, I would like to write a generic version of "waitForFnc" as I need to do the same in several places. Sort of

waitForFnc(Portal.Management_Init);

function waitForFnc(fnc) {
    if (typeof fnc == "undefined") {
        window.setTimeout(waitForFnc(fnc), 50);
    }
    else {
       fnc();
    }
}

where I pass the name of the function in which it is called when it becomes available. The above code does not work, but I'm not sure how to resolve it.

Relationship Gender

+3
source share
4 answers

, . waitForFnc() , Portal , null. , , , eval() * gasp *

, , .

function waitForFn(fnName, args){
    var fn;
    try{
        eval("fn = " + fnName);
        if(fn){
            fn.apply(null, args);
        }else{
            setTimeout(function(){waitForFn(fnName, args);}, 50);
        }
    }catch(e){
        setTimeout(function(){waitForFn(fnName, args);}, 50);
    }
}

waitForFn("Portal.Management_Init", [arg0, arg1]);
+2

, : window.setTimeout(waitForFnc(fnc), 50);, "waitForFnc" , -. .

:

window.setTimeout(function() {waitForFnc(fnc);}, 50);

, , :

var myFunc = function() {
    waitForFnc(fnc);
};

, . "setTimeout":

window.setTimeout(myFunc, 50);

"setTimeout" 50 . , waitForFnc(fnc).

+3

In the code, replace:

window.setTimeout(waitForFnc(fnc), 50);

with closure:

window.setTimeout(function() {waitForFnc(fnc)}, 50);

But may I ask, why do you need such a strange code? I would rather have an API that allows you to register a callback:

Portal.onManagementInitAvailable(fn);
0
source

Depending on what you download, you can use require.js to take care of this for you; which is mostly for him: http://requirejs.org/docs/why.html#9

0
source

All Articles