views:

90

answers:

1

Hey guys,

Iv'e just started a new Wordpress blog and i have started to build the JavaScript base!

the issue im having is that i have a fucntion that loops several variables and includes the required JS libraries, what i need to do is execute the callback when the loop is finished!

Heres 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!

+1  A: 

$.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();              
        });
    });
Andy E
Thanks Andy, perfect, i was thinking of deleting the array items but i wanted to also track what items have been loaded so if an ajax call comes in it will not load the JS if its already been loaded, that was the reason i never done this method but i can see i must do it, i just pass the `val` to another object as Loaded and everything is good :) | `library Loaded: fancybox All loaded` Desired output, thanks
RobertPitt