2

i have a avatar loading animation, which is getting swapped for the image when it is loaded :

  var avvy = $.trim("/"+this.mycoach.avatar);
    this.tmpImg = new Image() ;
    this.tmpImg.src = avvy;
    $(this.tmpImg).load( function() {
        $(contentDiv).find(".photo").css('background-image',"url("+avvy+")");
    });
}

it works - after the image is loaded the background is swapped for the avatar. however the browser then sends a new request to the same image....

the image url is like :

/avatar_fb.php?fbid=*****&width=80&height=80&token=3547***52

can i force the browser to cache that image ? or server side code ?

Mark Nottingham
  • 5,546
  • 1
  • 25
  • 21
n00b
  • 5,642
  • 2
  • 30
  • 48
  • jQuery is optional, just testing if it would work this way (no change compared to .onload ;/ ) – n00b Jan 24 '13 at 13:38
  • You might use it as `src` value but if you use it as a background image there seems to be no way right now: http://stackoverflow.com/questions/11907568/force-image-caching-with-javascript – jantimon Jan 24 '13 at 13:38
  • You can use jQuery `$.ajax` and set `cache: true` – Morpheus Jan 24 '13 at 13:47
  • 1
    I think you can append the image to .photo div ... $(contentDiv).find(".photo").append(this.tmpImg), but the image will be a dom element, not as a background of the .photo div. That way would work... – António Almeida Jan 24 '13 at 13:52
  • 1
    i ended up treating the "loading" div as a container and just pasting ` – n00b Jan 24 '13 at 13:52
  • Take a closer look at the network tab of your browser; it may well load it from the cache for the second load (in Chrome it would say `(from cache)`). – Ja͢ck Jan 24 '13 at 14:11

2 Answers2

1

Yes, you can do it with server-side code. Check out this other stackoverflow answer - specifically the snippet of PHP, for how to set a HTTP "Expires" header.

The query string at the end of the URL is what's causing the browser to not cache the file. The browser acknowledges that any URL with '?' after the filename is likely to by dynamic, and so it doesn't cache it. One solution would be to use URL rewriting so you fetch your images using a url like /avatar/<fbid>/<token>/<width>/<height>, essentially tricking the browser into thinking it's requesting static content, and therefore caching it.

Community
  • 1
  • 1
Erinaceous
  • 53
  • 4
1

As said in the comment: You can append the image to .photo div, using the element tmpImg, but the image will be a dom element, not as a background of the .photo div. That way would work.

Here is the fiddle: http://jsfiddle.net/wHPjJ/

tmpImg = new Image();
tmpImg.src = "http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=5";

$(tmpImg).load( function() {
    $(".photo").append(tmpImg); // this instead of tmpImg would also work
});
António Almeida
  • 9,620
  • 8
  • 59
  • 66