2

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.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Priyank Bolia
  • 14,077
  • 14
  • 61
  • 82
  • possible duplicate of [How to turn a String into a javascript function call?](http://stackoverflow.com/questions/912596/how-to-turn-a-string-into-a-javascript-function-call) – Brad Christie Mar 13 '12 at 18:28

2 Answers2

2

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]();
});
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
2

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.

rjz
  • 16,182
  • 3
  • 36
  • 35