getScript创建ReferenceError

时间:2015-07-17 09:05:21

标签: javascript jquery referenceerror getscript

在我开始其余代码之前,我有一些js脚本加载到我的main.js中。但是在测试过程中我注意到有时它会产生以下参考错误(8个页面加载中的1个)。

ReferenceError: createContainer is not defined

现在,我能想到我得到这个错误的唯一原因是当我执行startScript()函数时,并非所有文件都被加载或完全可访问。

现在,也许我将其他.js文件包含在我的main.js中是错误的,所以我想听听你对此的看法。

main.js看起来像这样:

$(document).ready(function() {

    //sets and array of files that should be loaded before anything every happens
    var arrFilesToLoad = [  'scripts/global/variables.js',
                            'scripts/global/objects.js',
                            'scripts/global/classes.js'];
    var _error;

    //walks through the array of items that should be loaded and checks for fails
    $.each(arrFilesToLoad , function (key) {
        $.getScript(arrFilesToLoad[key])
            //when a file is loaded with succes
            .done(function () {
                //on default send a message to the console
                console.log(arrFilesToLoad[key] + 'loaded succesfully');
                //if every item is loaded start the script
                if(key == (arrFilesToLoad.length - 1)){
                    startScript();
                }
            })
            //when a file fails to load
            .fail(function () {
                //add the file that failed to load to a string message
                _error += arrFilesToLoad[key] + " - failed to load. \n";
                //show an alert with what file failed to load
                if(key == (arrFilesToLoad.length - 1)){
                    alert(_error);
                }
            });
    });

    function startScript () {
        //set a variable which contains a function that returns a DIV with styling
        var oContainer = createContainer();
        var oMainMenu = new Menu(arrMainMenu);
        $(oContainer).append(createMenu(oMainMenu));
        $('body').append(oContainer);
    }

});

1 个答案:

答案 0 :(得分:4)

问题是因为您正在加载3个脚本,并且可能只有其中一个拥有createContainer()函数,但是在最后一个请求加载时您执行了代码。这意味着您已经遇到了竞争条件。最后一个请求不保证是最后一个完成的请求。如果在最终请求完成后仍在加载其他脚本,您将看到此错误。

您可以修改逻辑,以便仅在加载所有脚本后才执行回调。试试这个:

var requests = [];
$.each(arrFilesToLoad , function (key) {
    requests.push($.getScript(arrFilesToLoad[key]));
});

$.when.apply(this, requests)
    .done(startScript)
    .fail(function() {
        console.log('one or more scripts failed to load');
    });

function startScript() {
    var oContainer = createContainer();
    var oMainMenu = new Menu(arrMainMenu);
    $(oContainer).append(createMenu(oMainMenu));
    $('body').append(oContainer);
}