有条件地调用外部JavaScript文件

时间:2013-01-29 09:36:29

标签: javascript

是否可以根据以下条件调用外部javascript文件,例如

switch (VCheck) {
    case "1":
        Call "1.js"
        break;
    case "2":
        Call "2.js"
        break;
    case "3":
        Call "3.js"
        break;
    case "4":
        Call "4.js"
        break;
    case "5":
        Call "5.js"
        break;
    case "0":
        Call "Default.js"
        break;
    default: alert("Server Error - No Data!");
}

如果是这样,请帮助您提供正确的语法。

1 个答案:

答案 0 :(得分:2)

你应该使用require.js,它能以更优雅的语法完成你所需的工作。

http://requirejs.org/

如果您的“调用”指令执行异步加载,您也可以通过这种方式对代码进行分解:

function Call(VCheck, callback)
{
    callback = callback || function(data) {};

    var data = ["Default", "1", "2", "3", "4", "5"];
    if (VCheck < 0 || VCheck > data.length - 1) { return alert("Server Error - No Data!"); }

    var script = document.createElement("script");
    script.id = "data" + Math.ceil(Math.random() * 0xffffff).toString(16);
    script.async = true;
    script.type = "text/javascript";
    script.src = data[VCheck] + ".js";

    var head = document.getElementsByTagName("head")[0];
    head.insertBefore(script, head.firstChild);

    var img = new Image();
    img.onload = function()
    {
        //your data here
        console.log(document.getElementById(script.id).innerHTML);

        var data = document.getElementById(script.id).innerHTML;
        callback.call(null, data);
    };
    img.src = script.src;
}

或者如果你使用jQuery的getScript

$.getScript(data[VCheck] + ".js", function(data)
{
   //your data here
   console.log(data);
});