简体   繁体   English

发送函数名称,然后再加载?

[英]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. 我有这段代码,我在其中传递jsFile名称以进行加载,并在其中传递Java脚本函数。 But as the function is still not loaded, so I have to send string names and use this type of switch statements. 但是由于该函数仍未加载,因此我必须发送字符串名称并使用这种类型的switch语句。

$.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: 如果正在加载的脚本将这些定义为全局函数(使用a()b()似乎表明确实如此),则可以在浏览器中将window用作全局对象:

$.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. 当然,您需要确保脚本已成功加载,并调整回调函数的父级(在上例中为window )以适合您的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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