jQuery Ajax wait until all images are loaded jQuery Ajax wait until all images are loaded ajax ajax

jQuery Ajax wait until all images are loaded


The plugin that @alex wrote didn't work for me for some reason... I couldn't figure out why. But his code did inspire me to come up with a more lightweight solution that is working for me. It uses jquery promises. Please note that unlike @alex 's plugin, this doesn't attempt to account for background images on elements, only img elements.

// Fn to allow an event to fire after all images are loaded$.fn.imagesLoaded = function () {    // get all the images (excluding those with no src attribute)    var $imgs = this.find('img[src!=""]');    // if there's no images, just return an already resolved promise    if (!$imgs.length) {return $.Deferred().resolve().promise();}    // for each image, add a deferred object to the array which resolves when the image is loaded (or if loading fails)    var dfds = [];      $imgs.each(function(){        var dfd = $.Deferred();        dfds.push(dfd);        var img = new Image();        img.onload = function(){dfd.resolve();}        img.onerror = function(){dfd.resolve();}        img.src = this.src;    });    // return a master promise object which will resolve when all the deferred objects have resolved    // IE - when all the images are loaded    return $.when.apply($,dfds);}

Then you can use it something like this:

$.ajax({    cache: false,    url: 'ajax/content.php',    success: function(data) {        $('#divajax').html(data).imagesLoaded().then(function(){            // do stuff after images are loaded here        });    }});

Hopefully that's helpful for someone.

Note that using the above code, if one of the images errors (eg because the URL was wrong), the promise is resolved anyway and the error is ignored. This might be what you want, but, depending on your situation, you might instead want to abort whatever you are doing if an image fails to load. In which case you could replace the onerror line as follows:

img.onerror = function(){dfd.reject();}

And catch the error like this:

$('#divajax').html(data).imagesLoaded().done(function(){    // do stuff after all images are loaded successfully here}).fail(function(){    // do stuff if any one of the images fails to load});


You could use my jQuery plugin, waitForImages...

$.ajax({    cache: false,    url: 'ajax/content.php',    success: function(data) {         $('#divajax').html(data).hide().waitForImages(function() {             $(this).show();         });    }});

This will load the stuff into your element, hide it, and then reshow it once descendent img elements have loaded.


You can bind something to the load events to know when they're done:

$('<img>').bind('load', function() {    $(this).appendTo('body');});

Or you could use this plugin.