tags:

views:

293

answers:

4

I want to make an ajax call, but I want to make sure it will be cached. I am using jquery.

Is there a way to make sure the request stays in the cache for most popular browsers?

A: 

Set the appropriate headers on the http response, such as the Expires header,and the Cache-control directives.

See here for more details, but in a nutshell you want to set headers to indicate:

  • That the resource should be cached for a certain time (expires header)
  • That the resource is cacheable (Cache-control: public header)

Optionally, you may want to let the user request the file but send back a "not modified resposne", which saves on re-downloading the body (for large files). In this case you should use the response headers to indicate

  • When the resource was last modified (last modified time header), which allows the client to tell the server how old the version was
  • The E-Tag of the file, which is a sort of hash-code that lets the server know what version the client has. Be careful about how the e-tags are generated... on some servers the etags break load balancing.

The two approaches will let the client cache the response, and reduce the number of times the response is re-downloaded. Also, I like to avoid setting cookies in cacheable responses because some caches won't cache a response that has a cookie, and some caches cache the response including the cookie, both of which may be inappropriate.

Mr. Shiny and New
+1  A: 

I think all AJAX response are cached unless you specify not to cache. You can also check out jQuery Cache(?).

Shoban
+1  A: 

Hi,

GET requests may be cached by the browser (depending on browser cache size, and so on), but POST won't be cached.

Regards.

ATorras
+3  A: 

With jQuery, you will probably want to explicitly add the If-Modified-Since header with the ifModified option, which is false by default:

$.ajax({
     ...
     ifModified: true,
     ...
});

There's also a cache option that you'll need to force true if your dataType is jsonp or script. It's true by default for other dataTypes.

See the jQuery.ajax() docs for a description of these options.

Plutor