Cache AJAX Response

/ Published in: jQuery
Save to your folder(s)

Basically, if the value has already been requested once before it's returned immediately from the cache. Otherwise, an AJAX request fetches the data and adds it to the cache. The $.when/.then doesn't care about any of this; all you need to be concerned about is using the response, which is passed to the .then() handler in both cases.

Deferreds are perfect for when the task may or may not operate asynchronously, and you want to abstract that condition out of the code.

Copy this code and paste it in your HTML
  1. var cache = {};
  3. function getData( val ){
  5. // return either the cached value or an
  6. // jqXHR object (which contains a promise)
  7. return cache[ val ] || $.ajax('/foo/', {
  8. data: { value: val },
  9. dataType: 'json',
  10. success: function( resp ){
  11. cache[ val ] = resp;
  12. }
  13. });
  14. }
  16. $.when(getData('foo')).then(function(resp){
  17. // do something with the response, which may
  18. // or may not have been retreived using an
  19. // XHR request.
  20. });


Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.