开发者

how to make sure everything is loaded in ajax using jquery

开发者 https://www.devze.com 2023-01-20 05:25 出处:网络
Hello everyone I got trapped when Im using jquery loading some content into my page. The code is like this:

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

$("#holder").fadeout();
开发者_如何学C$("#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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消