javascript - getScript creates ReferenceError -


i have js scripts load main.js before start rest of code. during testing came attention creates following reference error (1 in 8 pageloads or something).

referenceerror: createcontainer not defined 

now, reason can think of error when execute startscript() function, not files loaded or accesable.

now, perhaps i'm going wrong including other .js files main.js, i'd hear thoughts this.

the main.js looks this:

$(document).ready(function() {      //sets , array of files should loaded before every happens     var arrfilestoload = [  'scripts/global/variables.js',                             'scripts/global/objects.js',                             'scripts/global/classes.js'];     var _error;      //walks through array of items should loaded , checks fails     $.each(arrfilestoload , function (key) {         $.getscript(arrfilestoload[key])             //when file loaded succes             .done(function () {                 //on default send message console                 console.log(arrfilestoload[key] + 'loaded succesfully');                 //if every item loaded start script                 if(key == (arrfilestoload.length - 1)){                     startscript();                 }             })             //when file fails load             .fail(function () {                 //add file failed load string message                 _error += arrfilestoload[key] + " - failed load. \n";                 //show alert file failed load                 if(key == (arrfilestoload.length - 1)){                     alert(_error);                 }             });     });      function startscript () {         //set variable contains function returns div styling         var ocontainer = createcontainer();         var omainmenu = new menu(arrmainmenu);         $(ocontainer).append(createmenu(omainmenu));         $('body').append(ocontainer);     }  }); 

the issue because you're loading 3 scripts , presumably 1 of them holds createcontainer() function, yet execute code when last request has loaded. means you've got race condition. last request made not guaranteed last 1 completed. if other scripts still being loaded final request completed, you'll see error.

you can amend logic callback executed once scripts have loaded. try this:

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 load');     });  function startscript() {     var ocontainer = createcontainer();     var omainmenu = new menu(arrmainmenu);     $(ocontainer).append(createmenu(omainmenu));     $('body').append(ocontainer); } 

Comments