views:

59

answers:

3

Hello,

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,

+4  A: 

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.
Pointy
+2  A: 

Try using the get method instead...

$.get("dynamic.php", function(result){
                $("#box_name").replace(result);
            });
VinTem
+1  A: 

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.

Brian Lacy
Except even if he uses jQuery.ajax, what's going to come back in the HTML fragment is an `<img>` tag that will cause **another** HTTP request. (That's assuming he's not trying anything fancy like a "data URL", which might be tricky with Ajax in IE.)
Pointy
I was actually thinking he'd return merely a URL path to an image file within the web root, and replace the image source directly with Javascript. You're still technically manipulating the DOM here, and you'd still want to pre-cache the image, but once it's loaded it's a snap to replace the img src.
Brian Lacy