Besides jQuery's AJAX functions I'm very limited in my understanding of "asynchronous" JavaScript.
I've created a system where I'm loading external Javascript files in as 'modules' in order to keep things tidy and lightweight. The main inspiration + implementation for doing this can be found here.
So, for example, a JS file called foo.js might contain the following JS object with set attributes:
var bar = {
a:1,
b:2
}
After this external file has been loaded it's accessible via window.bar thereafter. So typing in window.bar.a (alternatively bar.a) into the browser's Developer Tool JS console should return:
1
My issue arises when I try to assign the bar object to a variable, this will often be resolved synchronously before the external JS module has been loaded and usually contain undefined - boo!
This is my attempt so far: basically return the object instance if it already exists in the window, otherwise wait for it to be loaded and then return it (ideally):
var val = getInstance('bar');
Which calls my function:
function getInstance(name) {
if(typeof window[name] === 'object'){
return window[name];
} else {
$(window).on('load', window[name], function() {
return window[name];
});
}
}
Which, of course returns undefined when I console.log(val).
I know for a fact here that I'm expecting the object bar to come through asynchronously to val. To which I can then go ahead and start referencing the bar instance through val (i.e. val.a == 1).
I've made an effort to skim over jQuery's Deferred Object ($.Deferred) - to which my understanding disappears, but I'm on a tight deadline and would like to know now rather than a few days down the line if I'm on the right track in getting and instance of bar into val.
Any help, pointers or comments are much appreciated!