AJAX - AJAX Caching
1) What is AJAX Caching?
When you make an AJAX request (usually GET), browsers may cache the response to avoid repeated network calls.
-
This is great for performance (fewer server hits).
-
But it can be a problem when you need fresh data (like new messages, stock prices, or live updates).
So controlling caching means telling the browser (and sometimes proxies) when to store or ignore AJAX responses.
2) How Browsers Cache AJAX Responses
-
By default, GET requests can be cached.
-
POST, PUT, DELETE are usually not cached.
-
Whether caching happens depends on:
-
The request URL (including query string).
-
HTTP response headers (
Cache-Control,Expires,ETag, etc.). -
Browser settings.
-
3) Techniques to Control AJAX Caching
A) Disable Caching (always fresh data)
-
Cache-busting query strings
Add a unique parameter (like timestamp or random number) to the URL:fetch('/api/data?nocache=' + Date.now()) .then(res => res.json()) .then(data => console.log(data));This makes each request unique, so the browser won’t serve cached results.
-
HTTP Headers
Set headers on the server response to prevent caching:Cache-Control: no-cache, no-store, must-revalidate Pragma: no-cache Expires: 0Example in Express (Node.js):
res.set('Cache-Control', 'no-store');
B) Enable Caching (reuse results for performance)
Sometimes caching is desirable (e.g., static config, rarely-changing data).
-
Cache-Control header
-
Example: cache response for 1 hour
Cache-Control: public, max-age=3600 -
Browser will reuse the cached version until expiry.
-
-
ETag + If-None-Match
-
Server sends an ETag (unique version identifier for the resource).
-
On next request, browser sends
If-None-Match: <etag>. -
If unchanged, server responds with 304 Not Modified (saves bandwidth).
Example Express code:
res.set('ETag', hashOfData); -
-
Last-Modified + If-Modified-Since
-
Server sends
Last-Modified: <date>. -
Browser later asks
If-Modified-Since: <date>. -
If unchanged, server replies
304 Not Modified.
-
4) Example: Prevent Caching in jQuery AJAX
$.ajax({
url: "/api/data",
method: "GET",
cache: false, // jQuery automatically appends "_=timestamp"
success: function(data) {
console.log(data);
}
});
5) When to Use Caching vs No Caching
-
Disable caching for:
-
Live data (chat messages, stock prices, dashboards).
-
Sensitive data that should never be stored.
-
-
Enable caching for:
-
Static or rarely-changing data (config, country lists, help text).
-
Large assets you don’t want re-downloaded.
-
Summary:
-
AJAX caching can improve speed but risks showing outdated data.
-
Control it with query strings, response headers (
Cache-Control,ETag,Last-Modified), or library settings (likecache: falsein jQuery).