ajax cache

Creating your own AJAX cache

If you've made AJAX calls before, you know that they are subject to client-side caching, as specified by the server. Of course, you can request that the response not be cached (by passing the current timestamp in the query string, or using the jQuery cache parameter). What if we want more control though?

If a server doesn't specify HTTP caching, you are forced to make a round trip to the remote server with each request, regardless of whether you need updated information.

If anticipated responses are relatively small, it may make sense to create a client-side cache within your application.  This would allow you to encapsulate AJAX calls neatly into a cache-aware function. I've implemented a basic JavaScript cache below to demonstrate how one might go about this.

In my case, I use the app variable to namespace global variables specific to my application. Although, in my case, I've made the cache global, you could just as well maintain it as a private variable inside a "class" to further hide it's implementation details.

 

remoteCache: function(key, rpcURL, expireSeconds, callback) {
  var now = (new Date).getTime() / 1000;
  var expired = false;

  if (typeof app.remoteCache === 'undefined') {
    app.remoteCache = {};
  }

  if (typeof app.remoteCache[key] === 'undefined') {
    expired = true;
  }
  else if ((now - app.remoteCache[key].lastCall) > expireSeconds) {
    expired = true;
  }
  else {
    expired = false;
  }

  if (expired) {
    $.ajax({
      url: rpcURL,
      success: function(data) {
        app.remoteCache[key] = { value: data, lastCall: now };
        callback(data);
      }
    })
  }
  else {
    callback(app.remoteCache[key].value);
  }
}

 

Example cache-aware call

 

remoteCache('weather', 'http://myweatherservice.com?q=40.08,-71.50&format=json&num_of_days=2', 7200, function(result) {
    // this is the callback
    // I don't need to make a round trip to the weather server every time.  once every 2 hours (7200 seconds) would be enough
    document.write ( result.temperature );
});

 

AJAX calls are often bottlenecks to any app, even if requested asynchronously. You can see how this can drastically improve the responsiveness of your application if you don't need real-time data. 

Why follow me on Twitter?

  • I tweet about new technologies, services or libraries I find interesting
  • Yeah, sometimes I'll post a pet-peeve or rant about something trivial
  • If I discover something that made my web development life easier, I share it
  • I'll shout out any handy tip that I think might be useful to other devs
  • Very rarely anything promotional


Tagged , .

Updated: 2013-02-19

Phil LaNasa follow us in feedly