简体   繁体   中英

make sure an image is loaded while dynamically changing jquery

I'm changing the image src of an image node. I want to be able to make sure that it's changed before executing somecode. How would i do that?

right now i have

function changePic(imgNode, newPic, desc){
    var descNode = $("#description");
    $(imgnode).fadeTo(500, 0, function(){
        $(imgnode).attr("src", newPic);
        $(imgnode).attr("alt", desc)
        descNode.text(desc);
        $(imgnode).fadeTo(500, 1);
    });
}

Works great if the server's fast/ a local server. Works terribly if the server's slow, where the image will fade back in before changing...

any idea?

Edit: I'm loading the image when changePic is called. Any better ways to do it?

More: Also why is it not a good idea to put the last line,

$(imgnode).fadeTo(500, 1);

, outside of the callback function?

Preload the image , but to be sure it's completely loaded, use the .load() event .

Quote:

The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.

And don't miss this line:

It is possible that the load event will not be triggered if the image is loaded from the browser cache. To account for this possibility, we can use a special load event that fires immediately if the image is ready. event.special.load is currently available as a plugin .

I put together an example of how I think you want it to work. I switch between three images I found through Google Images. I bind the load event before I change the src of the image to be sure it's triggered. http://jsfiddle.net/xdjjR/1/

I guess, you can preload image in hidden elements, so that it's loaded with other html. When the source changed such image should be shown immediately.

Use the callback param doc ex from doc:

$('#clickme').click(function() {
 $('#book').fadeOut('slow', function() {
    // Animation complete.
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM