Wait with image replace until image is loaded

℡╲_俬逩灬. 提交于 2019-12-03 16:17:48

You could preload the image before attempting to display it...

$(".source a").click(function(e) {
    e.preventDefault();

    var newSrc = this.href,
        image = new Image();    

    image.onload = function() {
        $("#targetcontainer img").hide("puff", function() {
            $(this).attr("src", newSrc).show("fold");
        });
    }
    image.src = newSrc;
});
Jānis Gruzis

In JQuery there is load event.

1) Retrieve image.

var image = $("#img");
image.hide();

2) On load do something.

image.load(function(){
 image.show();
});

3) Change src attribute to fire load event after image has changed.

image.attr("src","image.jpg");

You can read more about it in here: http://api.jquery.com/load-event/

The best way to make this work in all browsers with the minimal amount of delay is to use CSS sprites.

If that's not an option for you, you could pre-load the image somewhere and make it invisible -- the browser will load the image early, and won't delay when your JQuery exectues.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!