Reputation: 57268
Iv'e just started a new Wordpress blog and I have started to build the JavaScript base!
the issue I'm having is that I have a function that loops several variables and includes the required JS libraries, what I need to do is execute the callback when the loop is finished!
Here's my code!
var Utilities = {
Log : function(item)
{
if(console && typeof console.log == 'function')
{
//Chrome
console.log(item);
}
},
LoadLibraries : function(callback)
{
$.each(Wordpress.required,function(i,val){
//Load the JS
$.getScript(Wordpress.theme_root + '/js/plugins/' + val + '/' + val + '.js',function(){ // %/js/plugins/%/%.js
Utilities.Log('library Loaded: ' + val);
});
});
callback();
}
}
And the usage is like so!
Utilities.LoadLibraries(function(){
Utilities.Log('All loaded');
});
Above you see the execution of callback()
witch is being executed before the files are in the dom! I need this called at the end of every library inclusion!
Upvotes: 1
Views: 1262
Reputation: 344575
$.getScript()
is an asynchronous call, so your javascript code will continue to execute until that call completes. As you already know, $.getScript()
also accepts a callback function as the success
argument, which will execute when the asynchronous call finishes. You will have to work your solution around that argument, possibly by removing the script from the array and then having a check to see if that array is empty.
$.each(Wordpress.required,function(i,val){
//Load the JS
$.getScript(Wordpress.theme_root + '/js/plugins/' + val + '/' + val + '.js',function(){ // %/js/plugins/%/%.js
Utilities.Log('library Loaded: ' + val);
// Remove the completed item
delete WordPress.required[i];
// If array is empty, all scripts loaded - execute callback!
if (!Wordpress.required.length)
callback();
});
});
Upvotes: 1