JavaScript: Deal with cached async calls

internet-explorer-fucking-sucks-internet-explorer-is-evilIf you are doing asynchronous calls to a server (AJAX or something else) you must know that some browsers will cache the result for a specific request.
The problem with that is that if you want to pull data from the server using repeated asynchronous requests then you are out of luck, the cache operation will cause your requests to return the same result for every call.

To fix this you can make sure that no asynchronous request is the same as other by appending the request timestamps as a URL parameter such as:

// this will be cached
GET example/stream/feed

// this won't be cached
GET example/stream/feed?timestamp=1452267544210

If you are using JQuery you can instruct JQuery to automatically append the timestamps to all requests by using this global function:

$.ajaxSetup({ cache: false });

2 thoughts on “JavaScript: Deal with cached async calls

  1. Yes, it should do the work in all modern browser If it’s set correctly in the server response. But if you want to deal with this on the client side, you don’t have that option. Also did I mentioned that it should work in all “modern” browsers? Sadly in some IE versions the cache control headers are ignored by the XMLHttpRequest. That said I think my next article will be about the recommended way to control the caching if you have the luxury to support only the sane browsers :).

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s