简体   繁体   中英

javascript callback after loop

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!

$.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();              
        });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM