views:

518

answers:

3

I have a web page where I want to switch the background image of a div in response to user interaction. What I have so far is:

function updateImg() { 
   imgurl=buildImgURL(); // constructs a URL based on various form values
   $('#mainImage').css("background-image", "url("+imgurl+")");
}

This works exactly like I want it to except for one thing. Due to a combination of relatively large background images and a relatively slow server (neither of which can easily be fixed) it takes a while for the image to load. So when the updateImg() function is called the div goes white for half a second or so before the new background image is loaded. What I want is for the old background image to remain until the new image is finished loading and then to switch instantly. Is this possible to do?

The background image is generated on the fly by the server so any sort of client side caching or preloading isn't possible.

A: 

You could define a CSS class with the background-image property set to the image, and then in your updateImg() function, set the class of that div instead of directly modifying the property. This might alleviate the problem.

Something like:

function updateImg() { 
  imgurl=buildImgURL(); // constructs a URL based on various form values
  $('#mainImage').addClass('imageClassName');
}

And then in your CSS:

.imageClassName {
  background-image: url([url to image]);
}
Peter
That wouldn't be possible if the image is created on the fly by the server based on user input...
peirix
Oops, didn't realize that the BG image was going to be generated based on user input.
Peter
A: 

Since you can't prefetch your image, you can do this:

  1. prefetch a "loading.." image
  2. set the "loading.." image as the background of your div while your actual image is cooking
  3. once your actual image is available, do your stuff.

Please don't ask me to write jQuery for it. Its simple enough :)

Cheers,

jrh.

Here Be Wolves
+1  A: 

What about setting the image to an empty element?

$("<img id='loaderImg' src='"+imgUrl+"' onload='setBg(this.src)'/>");

Then when the image is loaded

function setBg(imgUrl) {
    $("#mainImage").css("background-image", "url("+imgUrl+")");
    $("#loaderImg").remove();
}

This way, the image would be loaded into an image that will never be displayed, and set to the background when the image is fully loaded (and also cached)

Haven't tested this, but I think it should work.

peirix
Perfect. Exactly what I was trying to do