开发者

preload image and show a spinner while loading

Hy,

i use uploadify to upload some images, after i display all the images thumbs in a list, when i click on a image thumb a bigger image it's open in a div with this function

$(".thumbs li a").click(function(){
    var largePath = $(this).attr("href");
    $('.thumbs li').removeClass('thumbac');
    $(this).parent().addClass('thumbac');
    $("#largeImg").attr({ src: largePath });
    return false;
});

here is my list of photos:

<div class="upimage">
  <ul id="upimagesQueue" class="thumbs">
    <li id="liupimages">
      <a href="uploads/0001.jpg"><img src="uploads/0001.jpg" alt="0001.jpg" id=""></a>
    </li>
    <li id="liupimages">
      <a href="uploads/0002.jpg"><img src="uploads/0002.jpg" alt="0002.jpg" id=""></a>
    </li>
    <li id="liupimages">
   开发者_JAVA技巧   <a href="uploads/0003.jpg"><img src="uploads/0003.jpg" alt="0003.jpg" id=""></a>
    </li>
<script>
$(".thumbs li a").click(function(){
    var largePath = $(this).attr("href");
    $('.thumbs li').removeClass('thumbac');
    $(this).parent().addClass('thumbac');
    $("#largeImg").attr({ src: largePath });
    return false;
});
</script>
  </ul>
</div>

this is the div where the images appear

<div class="largeImg" >     
    <img id="largeImg" src="" />
</div>

how i can preload the image before it display?


You can somehow harness the load event, e.g.:

$(".thumbs li a").click(function(){
    var largePath = $(this).attr("href");
    $('.thumbs li').removeClass('thumbac');
    $(this).parent().addClass('thumbac');
    $("#largeImg").hide()
                  .attr({ src: largePath })
                  .load(function() {
                       $(this).show();
                   });
    return false;
});


here is how you can preload images in jq:

    (function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)

and then you preload them like this:

jQuery.preLoadImages("image1.gif", "/path/to/image2.png");


You can use my plugin imgPreload which while preloading an image displays a nice spinner.

In your case you would just need to add one line to your existing code:

$("#largeImg").attr({ src: largePath }); //your code
$("#largeImg").imgPreload() //the extra line

Please see this page http://denysonique.github.com/imgPreload/ for a demo and documentation.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜