Tom Brunoli
Tom Brunoli

Reputation: 3476

load() sequentially, instead of at the same time with jQuery

I'm developing a site where I want to get all the links from a navigation bar, and load a div from the linked pages into a big container. What I have so far is the following:

$('nav a').each(function(index){
    var to_load = $(this).attr('href') + '#slides section';
    $('<section>').load(to_load, function(){
        $('#slides').append($(this).html());
    });
});

This works great, apart from the fact that it is almost alway out of order, probably due to loading it asynchronously. Is there a way to load each at a time, so the sections will be in order, while still keeping it flexible?

Thanks heaps in advance!

Upvotes: 3

Views: 774

Answers (4)

karim79
karim79

Reputation: 342795

You create a recursive function which calls itself whenever .load completes, thus guaranteeing order:

// grab array of links
var links = $('nav a').map(function() {
    return this.href;
}).get();

function loadSlides() {
    $('<section>').load(links[0] + '#slides section', function() {
        $('#slides').append($(this).html());

        // remove first item of links array
        links.shift();
        loadSlides();
    });
}

loadSlides();

Upvotes: 0

mkilmanas
mkilmanas

Reputation: 3485

async: false may be an option, as mentioned by @marcosfromero

You might as well try another option of calling load after the previous one completes (well, that looks a lot like async:false)

var i = -1;  // this is because we will increment the value before using it
var collection = $('nav a');

function loadNext() {
    i++;
    if (i < collection.length) {
        var to_load = $(collection[i]).attr('href') + '#slides section';
        $('<section>').load(to_load, function(){
            $('#slides').append($(this).html());
            loadNext();
        });
    }
}

loadNext();

Upvotes: 0

Boris S
Boris S

Reputation: 311

var loadTos = [];
$('nav a').each(function(index){
    loadTos.append($(this).attr('href') + '#slides section');
});
function load_link(to_load) {
    $('<section>').load(to_load, function(){
        $('#slides').append($(this).html());
        loadTos.length && load_link(loadTos.pop());
    });
}
if(loadTos.length) {
   loadTos = loadTos.reverse(); // make getting urls from first to last
   load_link(loadTos.pop());
}

This code will load urls in chronological order. And they will be loaded one by one.

Upvotes: 0

marcosfromero
marcosfromero

Reputation: 2853

I'd try with async: false mentioned jQuery.ajax documentation. Don't know if it works with load but I'd bet it does.

Also, for performance reason, don't use:

$(this).attr('href') + '#slides section'

but

this.href + '#slides section'

To avoid converting this into a jQuery element (you only need it to get the href attribute).

Upvotes: 2

Related Questions