-1

我正在从远程服务器加载图像。我如何确保所有图像都以正确的顺序加载

另外我如何确保仅在加载所有图像时才调用警报

以下代码未按正确顺序加载图像,并在加载图像之前调用警报。

$(window).load(function () {
  $('.fancybox').each(function () {
    var hh = $(this).attr('href');
    var img = new Image();
    img.src = hh;

    function TIMG(i) {
      if (img.complete != null && img.complete == true) {
        $('.mag').append('<img src="' + hh + '" class="cls" />');
      } else {
        setTimeout(TIMG, 1000);
      }
    }

    setTimeout(TIMG, 1000);    
  });

  alert(hi);
});
4

2 回答 2

1

Based on the new information that you just want to add them in order as soon as they are ready, you can do that like this

 $(document).ready(function () {
      // preload all the images as fast as possible
      var imgs = [];
      $('.fancybox').each(function () {
          // get all images preloading immediately
          // so there is the best chance they are available when needed
          var img = new Image();
          imgs.push(img);
          img.onload = function() {
              addReadyImages();
          }
          img.className = "cls";
          img.src = $(this).attr('href');
      });

      function addReadyImages() {
          // show all images that are ready up to here
          while (imgs.length && imgs[0].complete === true) {
              // append the loaded image from the start of the array
              $('.mag').first().append(imgs[0]);
              // remove the one we just did from the start of the array
              imgs.shift();
          }
      }
 });

Working demo: http://jsfiddle.net/jfriend00/sCHws/

This algorithm works as follows:

  1. Start preloading all the images as soon as possible.
  2. Store the image objects in an array in the order that the .fancybox items are encountered in your page
  3. Set an onload handler for each image so we know immediately when it's ready
  4. In the onload handler for any image, append all images at the front of the array that are ready and then remove them from the array

P.S. I've assumed there is only one .mag item and thus we don't need to make separate copies of the image objects (much more efficient that way - rather than creating new image objects). If that is not the case, then please disclose your HTML so we can see the whole problem.

于 2012-09-30T21:28:08.050 回答
0

由于浏览器在下载图像时通常不会阻塞,因此确保以正确顺序加载图像的唯一方法是串行加载它们……使用队列,然后在前一个完成后才开始下一个。绝对不建议这样做,因为这很容易造成严重的性能损失。

等待所有图像加载的时间最好通过.promise()jQuery 中的相关方法来完成:http: //api.jquery.com/promise/,并观察图像何时被load()编辑。如果您特别想控制图像的显示(这很可能是您所关心的),那么它们可以在加载后按顺序显示。

于 2012-09-30T21:06:21.110 回答