在函数中途停止加载脚本

时间:2014-05-08 07:20:36

标签: javascript

这是我的JS文件:

function loadScripts(){
    var scripts = ['a.js', 'b.js', 'c.js'];
        for (i=0; i<scripts.length; i++){
            var script = document.createElement('script');
            script.src = scripts[i];
            head.insertBefore(script, head.firstChild);
    }
};

function Formatter(){

    setTimeout(function(){loadScripts()},1000);

    this.instantiate = function(){
        return this;
    };

    this.func1 = function(){
        ...
    };

    this.func2 = function(){
        ...
    };

};

func2使用要加载的脚本内部的变量,并且抛出一个错误,指出该变量未定义。我无法停止处理以加载脚本。我该怎么做?从JSP调用函数Formatter(),然后调用instantiate()方法。

3 个答案:

答案 0 :(得分:2)

实现了这个:

function loadScripts(scripts)
{
    var isXDR = window.XDomainRequest;
    for (i=0; i < scripts.length; i++)
    {
        var xhrObj = new XMLHttpRequest(),
            vURL = scripts[i];
        xhrObj.open('GET', vURL, false);
        xhrObj.send('');
        var se = document.createElement('script');
        se.type = "text/javascript";
        se.text = xhrObj.responseText;
        head.insertBefore(se, head.firstChild);
    }
};

function Formatter()
{
    var scripts = ["a.js", "b.js"];
loadScripts(scripts);

...
};

答案 1 :(得分:0)

这是我的JavaScript加载程序

var meorg = new Object();


var urls = new Array(
   'files',
   'calendar',
   'scheduler',
   'alert',
   'private',
   'main'
);


meorg.path = '/themes/meorg2/js/meorg.'

meorg.loadScript = function (urls) {
 if (urls.length === 0) return false;
 var _self = this;
 var url = urls.shift();

 var body = document.getElementsByTagName('body')[0];
 var script = document.createElement('script');
 script.type = 'text/javascript';
 script.src = this.path + url + '.js';

 script.onload = function () {
    _self.loadScript(urls);
 };
 body.appendChild(script);
 }
meorg.loadScript(urls);

以此为例。

答案 2 :(得分:0)

如果我找对你,你想暂停一个函数的执行,直到另一个函数完成。试试这个

Wait till a Function with animations is finished until running another Function