Detect when a set of deferred ajax requests have finished loading, and the page has also finished loading using jQuery

StackOverflow https://stackoverflow.com/questions/21953902

Question

I can detect when an array of deferred AJAX requests are finished using jQuery, and I can detect when the page loads using jQuery.

But I can't seem to detect both at the same time.

Here's what I've got:

$(function () {
    var getscriptlist = ['js/libs/handlebars.js', 'js/libs/ember.js', 'js/libs/prefixfree.js'];
    var deferreds = [];
    for (var i = 0; i < getscriptlist.length; i++) {
        deferreds.push($.getScript(getscriptlist[i]));
    }
    $.when.apply($, deferreds).then(function () {
    });
});

But I want the AJAX requests to run before the page starts loading, and then I want to fire something when the document has loaded as well.

My current problem is that the page loads, and the AJAX will take too long, as it starts running only after the page loads. If I switch it the other way round (so that the requests are fired, and when they're done and the page has loaded), then maybe the AJAX requests take too long, and delay the execution of scripts on the page, which bind to inside the $(function, which is run when the page finishes loading.

Any help? Thanks.

Was it helpful?

Solution

I guess there's a number of ways to do this. Here's one :

$(function () {
    var getscriptlist = ['js/libs/handlebars.js', 'js/libs/ember.js', 'js/libs/prefixfree.js'];
    var deferreds = [ $.Deferred() ];//<<<<<< start the array with a special Deferred 
    $(window).on('load', deferreds[0].resolve);//<<<<<< resolve the special Deferred when the page has loaded
    for (var i = 0; i < getscriptlist.length; i++) {
        deferreds.push($.getScript(getscriptlist[i]));
    }
    $.when.apply($, deferreds).then(function () {
        //code here will run when all Deferreds/promises in the array become resolved.
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top