简体   繁体   中英

Send function name, before they are loaded?

I have this code, where I pass the jsFile name to load and the java script function to call in it. But as the function is still not loaded, so I have to send string names and use this type of switch statements.

$.getScript(jsFile, function() {
    switch(initFunc){
        case 'a':
            a();
            break;
        case 'b':
            b();
            break;
    };
});

Is there anyway this can be simplified, I don't want conditional statements.

If the script being loaded defines these as global functions (which the use of a() and b() seems to suggest it does), you can utilize window as the global object in browsers:

$.getScript(jsFile, function () {
    window[initFunc]();
});

You could pass both the name of the script and the name of the callback function to a wrapper that looks something like this:

function loadNExecute(scriptName, callbackName) {
  $.getScript(scriptName, function() {
    window[callbackName]();
  });
}

You would of course need to ensure that the script is loaded successfully and adjust the parent of the callback function ( window , in the example above) to suit your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM