Goro
Goro

Reputation: 10249

Holding old image until new image is ready to update

I am using setInterval and the jQuery load function to periodically update an image tag.

var refresh_days = setInterval(function() { 
  $('#box_name').load("dynamic.php");}, 1000 );

This works, but there is a slight delay before the new image is fully loaded, during which nothing is shown.

Is there a way I can wait until the new image is loaded completely, and then display it, so that the image changes instantaneously from the user's perspective?

My target browser is Chrome and I do not need this to be compatible with IE.

Thanks,

Upvotes: 0

Views: 617

Answers (3)

thitemple
thitemple

Reputation: 6059

Try using the get() method instead...

$.get("dynamic.php", function(result){
    $("#box_name").replace(result);
});

Upvotes: 2

Pointy
Pointy

Reputation: 413808

You could load the image into an invisible <img> tag, and use the "load" event to update the visible one.

$('#hiddenImage').attr('src', newImageUrl).load(function() {
  $('#realImage').attr('src', newImageUrl);
});

That way you know it's in the cache, so the update to the visible image should be pretty quick.

If you're reloading a whole chunk of stuff, then you're going to have problems because the "load" action will update the page and then the browser will start the HTTP transaction to satisfy the implicit "GET" request in the <img> tag. What you could do, therefore, is:

  1. Load the whole blob into a hidden <div>
  2. Have a live() handler waiting for the "load" event from the image tag in the hidden div;
  3. React to the "load" event by moving the DOM subtree from the hidden div out to the place you really want it.

Upvotes: 5

Brian Lacy
Brian Lacy

Reputation: 19098

I'm thinking .load may be causing problems for you since you're actually reloading the entire HTML structure within that section of your HTML code.

Instead of using .load, I'd try using the jQuery.ajax() method. Attach a method to the success option which takes the returned image and swaps it in over the old one. This way, you're just using CSS to swap out the image rather than manipulating the DOM.

Look at http://docs.jquery.com/Ajax/jQuery.ajax#options for more info.

Upvotes: 1

Related Questions