1

Hello everyone I got trapped when Im using jquery loading some content into my page. The code is like this:

$("#holder").fadeout();
$("#holder").load("test.html", callbackfn);

function callbackfn(){
    $("#holder").fadein();
}

test.html

<div style="background-image:url(1.jpg);">test</div>

That's the main idea, and actually it works quiet fine except that #holder is faded in before pictures are fully loaded. How can I make sure everything in test.html is fully loaded before #holder is displayed?

Cauly
  • 370
  • 1
  • 2
  • 12

2 Answers2

0

Images are loaded in their own request. So even though you are loading the image via ajax, once they are placed in the DOM, they perform their own request to fetch the image. There is an onload event you have access to on the IMG. So you'll need to know how many images you are expecting and then somehow track which ones are complete, then perform your fadein.

Gregg
  • 34,973
  • 19
  • 109
  • 214
  • 1
    [ Written by [ **Jason Bunting in this comment** ](http://stackoverflow.com/questions/280049/javascript-callback-for-knowing-when-an-image-is-loading/280087#280087) ] FYI: According ot the W3C spec, onload is not a valid event for IMG elements. Obviously browsers do support it, but if you care about the spec and are not 100% sure all of the browsers you want to target support this, you may want to rethink it or at least keep it in mind. --------------- [ **MDC onload ref** ](https://developer.mozilla.org/en/DOM/window.onload) - note how it states that `onload` is a property of just `window`. – Peter Ajtai Oct 15 '10 at 03:48
0

This would be a bit tricky, if you have many images. My best guess, since you didn't provide test.html, is this.

$("#holder").load("test.html", cbLoaded);

function cbLoaded(){
  var onLoadCount = $("img","#holder").length;
  var count = 0;
  $("img","#holder").bind("load",function(){
    count++;
    if( count === onLoadCount ){
      //Everything loaded!
    }
  });
};

This will work with >=1 images, if you have one image just use the bind("load") and forget the counting business.

Drew
  • 4,683
  • 4
  • 35
  • 50
  • That's a good idea, but what if the picture is a background-image?(
    test
    )
    – Cauly Oct 15 '10 at 05:00
  • No dice, I'm unaware of a way to check for background-image. I will look around for this and post if I find something useful. – Drew Oct 15 '10 at 21:35