开发者

Image load by jQuery

We have image and links in separate blocks.

When link is clicked, its href attribute puts to src of the image.

What I'm trying to do:

If image is not already loaded (not cached) {
    fadeOut previous image {
        fadeIn loader {
            load image (when animation of loader ends) {
                fadeOut loader {
                    fadeIn image
                }
            }
        }
    }
} else (if image is cached, do not show loader) {
    fadeOut previous image {
        fadeIn new image
    }
}

Here is what I have: http://jsfiddle.net/EvXJr/13/

First part works, don't know how to code the second (else) part.开发者_开发问答

Please help.


The dirty way would be to assign ids to loaded images, if there is no element with such id on a page - show loader, else just animate image.

Example: html:

<div id="container">
   <a href="http://www.site.com/image.png" id="smid1"></a>
   <a href="http://www.site.com/image.png" id="smid2"></a>
</div>

js:

$('#container').delegate('a', 'click', function () {
   var sel_id = this.id;
   if (!document.getElementById('img_' + this.id)) {
      //create image with  id  like: sel_id = 'img_' + this.id
   } else {
      //just show image
   }
});


Why don't you just keep track of what HREFs you have loaded with a javascript array that you have loaded and if your HREF can be found in the loaded array just take out the loader related functions.


Couldn't get the jsfiddle to load but if I understand correctly I would just set the background image of the element that holds the images to a loading gif then you don't have to worry about fading in and out a loader. If an image is already cached it will load so quickly you will never see the loading gif. And if it isn't and takes a while to load the user will see the loading gif and using the function below the image will fade in nicely once loaded.

And if you want to perform a function once an image has loaded use

$("img").load(function(){
    //do stuff once image has loaded.
    //for example
    $(this).fadeIn("slow");
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜