0

Possible Duplicate:
jQuery Ajax wait until all images are loaded

I want to have my images loaded first in my ajax call first before showing. How do I do that?

$.ajax({
   url: 'ajax.php',
   type: 'post',
   data:  "q="+query,
   success: function(data) {

     $('.show').html(data).fadeIn('fast');

   }
});

I'd like to have a clean fadeIn of my ajax but right now its showing up right away and my texts are completely loaded but my images are loading slowly and gets loaded from top of page to bottom page.

Ideally i'd like to show a loading symbol and then have a clean fadeIn when my images are loaded in the background.

Thanks!

Community
  • 1
  • 1
hellomello
  • 8,219
  • 39
  • 151
  • 297

1 Answers1

1

Add an event listener to the image load and error events to count the loaded images event

success: function(data) {
    var count = 0;
    var images = $('.show').html(data).find('img').on('load', function(){
        count++;
        if (count == images){
            $('.show').fadeIn('fast');
        }
    }).on('error', function(){
        count++;
        if (count == images){
            $('.show').fadeIn('fast');
        }
    }).length;
}
Musa
  • 96,336
  • 17
  • 118
  • 137
  • it seems to not work as predicted. Would it matter if i'm displaying it based on a foreach loop inside the ajax.php that i'm fetching? – hellomello Jan 28 '13 at 00:29