Liam Green-Hughes

cache busting in jQuery when you are not allowed a timestamp parameter

The jQuery ajax() method has a great feature where you can choose to cache a response to a web query called from your script. Caching the response is generally a good idea as it can help improve performance, but there may be times when your application knows it needs a fresh copy of the data, maybe because it has uploaded a change or an action has taken place that will have caused that data to change.

There is one potential issue that can cause an issue; If you set the cache property to false, jQuery will append an extra parameter to the URL of your request in the format _={timestamp}. This is great as long as the service you are calling doesn’t mind the extra parameter. However some services, including our own Atlas, do mind and raise an error when they see this unexpected parameter. Atlas does not allow random parameters as it aims to help users with suggested parameters if they get a name wrong.

Fortunately this issue is fairly easy to get round. If you are using the JSONP data type option you can neatly sidestep this whole issue by manipulating the callback function name that gets passed to the web server. To do this you specify the jsonpCallback option to a generated name based on the timestamp. Note the cache option is still set to true to avoid jQuery appending the generated parameter, so you will want to add a comment to make it clear you are not caching. You will probably end up with something like the code snippet below.

blog comments powered by Disqus