jQuery load function ignores Cache-Control max-age

1.5k views Asked by At

I am using jQuery's load function to get an image (graph) from my server. The graph is received from a REST API protected with Basic Authentication. The image is in the current setup returned with header Cache-Control max-age=0. This is respected if I call the image url directly from the browser. But when using jQuery's load function, it is cached.

I don't want to get a new image every time, because it requires some heavy calculations on the server, and because the graphs shows real-time data, long time caching is unwanted. I will use max-age=30 or 60 later.

I know jQuery's ajax function has a cache option. But this option can only be set to true or false, and that's not what I'm looking for.

1

There are 1 answers

1
odrm On

The standard way to override getting a cached result is to append a random query string to the URL you're getting, as in:

$(this).attr('src', url + '?randomval=' + (new Date).getTime() );

You can then set the server headers to allow the client to cache (e.g. Cache-Control: private - or whatever is appropriate for your application), and decide in your javascript code how often you want to change the "random" value appended to your URL to force the resource to reload.