tags:

views:

148

answers:

2

The title pretty much says it. I have an element that doesn't have a background image. I set one (a spinner) during an Ajax request using jQuery's css() method, then clear it with removeAttr("style") to revert back. Only one request is running at a time.

This, however, causes a GET for the background image not just the first time, but later as well, but even then, not always. I may send, let's say, 5 requests and no GET for spinner.gif after the first, then another request and there will be one, then not for another 3 request, then GET for the next 2.

If there was a GET for the image with every Ajax request, I'd understand, but it's kind of random.

What am I missing here?

+1  A: 

can't be sure without seeing your code, however you might consider playing it a little bit differently: option a: have two different css classes, one with the spinner, one without, and instead of playing with the background style param, just switch classes. option b: have the spinner there all the time, however make the container .hide(), then .show() it during ajax calls, and .hide() when they end.

Ken Egozi
+1  A: 

Firstly, make sure your server isn't stopping the browser caching the image.

Secondly, as Ken says it's generally better to switch a class on and off, and then use addClass and removeClass functions in jQuery. Using removeAttr('style') seems a bit hacky to me, and could remove other styles you don't want to remove.

If the above doesn't fix your problem, you could always try preloading the image:

var spinner = new Image;
spinner.src = "/path/to/image.gif";
// when you need to set the image...
$('#image').css('background-image', spinner.src);
// when you need to remove the image...
$('#image').css('background-image', '');
DisgruntledGoat