Raoulito
Raoulito

Reputation: 361

Change image with jQuery and see image getting loaded

I am dynamically changing images with jQuery using $('img').attr('src','newUrl');

Doing so, the image is only displayed when entirely loaded.

My connection is slow, so I would like the image to directly display and see it getting progressively loaded, the same way images “appear” when I arrive on any page on the web (whether from top to bottom, or from blurry to sharp depending on the compression algorithm of the image).

I want to do this with javascript, jQuery, or any simpler alternative.

(I know how to display a progress bar, or a "loading…" text while the image loads, that's not what I'm looking for)

Here's a fiddle if you want to update.

Upvotes: 1

Views: 307

Answers (2)

Sim
Sim

Reputation: 3317

I've found a way to do that, what you want. Don't use attr("src",) from jquery, remove and add the hole img element with html(), so you trigger the browser to load the image source and the browser displays the image while loading (tested in chrome).

Html:

<p><button>change image source</button></p>
<div>
    <img src="http://xxxxx">
</div>

Script:

var newImg = '<img src="http://yyyyyy">';

$('button').click(function(){
    $('div').html(newImg);
});

Here is your updated fiddle: http://jsfiddle.net/jxwv52u7/1/ I hope it helps.

Upvotes: 1

Ivin Raj
Ivin Raj

Reputation: 3429

Based on some testing I did about a year ago, I found no reliable way to get a load event when changing the .src of an image from one value to another. As such, I had to resort to loading a new image and replacing the one I had with the new one when the new image was loaded. That code has been running successfully in several hundred web sites (it's used by a slideshow) for about a year now so I know it works.

If you set the load handler BEFORE you set the .src property on a new image, you will reliably get the load event. Here's some code I wrote just earlier today for capturing the load event: jQuery: How to check when all images in an array are loaded?.

This code that attaches the event handler BEFORE settings the .src works for me in the modern browsers I've tried it in (I didn't test older browsers):

 $("img").one("load", function() {
        // image loaded here
    }).attr("src", url);

You can see it work here:DEMO and you can test any browsers you want using that jsFiddle. Just click on the image to cause it to load a new image. It cycles through three different images (setting .src each time), loading two of them uniquely every time (never from the cache) and one from the cache in order to test both cases. It outputs a msg to the screen whenever the .load handler is called so you can see if it's called.

Upvotes: 0

Related Questions