Load () sequentially, not simultaneously with jQuery

I am developing a site where I want to get all the links from the navigation bar, and load the div from the linked pages into a large container. So far, I mean 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, except that it almost always failed, possibly due to its asynchronous loading. Is there a way to load each at a time, so the partitions will be in order, while maintaining flexibility?

Thanks for the heaps in advance!

+3
source share
4 answers

I would try with async: falsemention jQuery.ajax documentation . I don’t know if this works with load, but I would say that it is.

Also, for performance reasons, do not use:

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

but

this.href + '#slides section'

this jQuery ( href).

+2
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());
}

URL- . .

0

async: false may be an option as pointed out by @marcosfromero

You can also try another load invocation option after completing the previous one (well, this is very similar to 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();
0
source

You create a recursive function that calls itself whenever it .loadcompletes, thereby 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();
0
source

All Articles