Home > Software design >  Delete cache of specific XHR call
Delete cache of specific XHR call

Time:09-23

I have a XMLHttpRequest that does a GET request:

const xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "myapi/getThing", true)

Normally, the response stays the same so the server instructs to cache it with a HTTP response header:

Cache-Control: public, max-age=604800, immutable

However, now I perform an action that I know for a fact will change the response, and so I call a XMLHttpRequest again, but the result won't change because of caching.

How do I make it so the next XHR call of this resource won't use the browser cache?

I have tried setting the Cache-Control to no-cache on the request:

xmlHttp.setRequestHeader("Cache-Control", "no-cache, no-store, max-age=0")

But the browser still uses the cache.

The goal is to explicitly NOT change the caching policy the server sets for performance reasons, so no validation and such. This should purely be the client wanting a 'fresh resource' on demand.

CodePudding user response:

An effective solution:
Cache busting via params
Assuming the server supports adding a useless parameter.

CodePudding user response:

I think both options could work, with cache busting as @Fudge Fudge suggested being the most frequently deployed one, something like:

xhtp.open("YOUR_METHOD","your_url?" (Math.random() * 1e16).toString(16))

or you can use Date.now() etc., its up to you, sufficiently random number to guarantee uniqueness is enough.

The other way, would be to:

xhtp.setRequestHeader("Cache-Control","no-cache, no-store, must-revalidate");
xhtp.setRequestHeader("Pragma","no-cache");
xhtp.setRequestHeader("Expires","0");

sometimes old headers like Expires etc. can get the job done.

  • Related