Search code examples
javascriptjquerysleepjquery-load

JQuery load function for group of links one by one?


I have an ul which contains many links. when using jQuery to load these links, it renders them all at same time. How can i load them one by one, having attempted the following:

js:

$('#publish').click(function() {
    $('#get_links li').
        each(function() {
            $(this).load('test.php',{'post':$(this).text()});
            $(this).html("<i class='icon-spin icon-spinner'></i>Loading");

            ///NEED TOSLEEP UNTILL $.load finish..
        }
        );
     }
);

How can i sleep the .each loop until .load finish ?


Solution

  • You can use the $().load callback for this:

    $('#publish').click(function(){
        var $link = $('#get_links li').first();
    
        var loadLink = function() {
            $link.load('test.php', { post: $link.text() }, function() {
                // once loading is done, grab the next link...
                $link = $link.next();
                // ... and load it if we found one
                if ($link.length) loadLink();
            }).html('<i class="icon-spin icon-spinner"></i>Loading');
        };
    
        // load the first link
        loadLink();
    });