GetScript throws a ReferenceError
I have a few js scripts that I load into mine main.js
before running the rest of the code. However, it occurred to me during testing that sometimes it generates the following pivot error (1 of 8 pageloads or whatever).
ReferenceError: createContainer is not defined
Now, the only reason I can think that I am getting this error is because when I execute a function startScript()
, not all of my files are loaded or fully accessible.
Now, maybe I'm going to do this all wrong for including other .js files in mine main.js
, so I'd love to hear your thoughts on that.
The main.js file looks like this:
$(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);
}
});
source to share
The problem is that you are loading 3 scripts and presumably only one of them contains a function createContainer()
, but you are executing your code when the last request is loaded. This means that you have a race condition. The last request that was made is not guaranteed to be the last one to be completed. If the rest of the scripts are still loading when the final request completes, you will see this error.
You can change your logic so that the callback is only executed after all scripts have loaded. Try the following:
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);
}
source to share