Rik Heywood
Rik Heywood

Reputation: 13972

How can I guarantee that an ajax response will be cached?

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?

Upvotes: 3

Views: 3360

Answers (4)

Plutor
Plutor

Reputation: 2897

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.

Upvotes: 8

Mr. Shiny and New 安宇
Mr. Shiny and New 安宇

Reputation: 13908

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.

Upvotes: 1

ATorras
ATorras

Reputation: 4293

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

Regards.

Upvotes: 2

Shoban
Shoban

Reputation: 23016

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

Upvotes: 1

Related Questions