Recently I wanted to cache the results (responseText) from a lot of Ajax.Requests since the returning data would not change and made the roundtrip to the server unnecessary. Maybe there are others out there interested so here’s the code. It’s not very well tested except the project where it is in use so there might be some bugs or tweaks needed.


Ajax.CachedRequest = Class.create(Ajax.Request, {
  initialize: function($super, url, options) {
    options = options || {};
    var onSuccess = options.onSuccess || Prototype.K;
    if (!Ajax.CachedRequest.cache[url] || options.reload) {
      options.onSuccess = function(transport) {
        Ajax.CachedRequest.cache[url] = transport.responseText;
        onSuccess(transport);
      }
      $super(url, options);
    } else {
      eval(Ajax.CachedRequest.cache[url]);
      this.dispatch.defer();
      [onSuccess, options.onComplete].each(function(m) { m && m() });
    }
  },

  dispatch: function() {
    Ajax.Responders.dispatch('onComplete', null);
  }
});

Ajax.CachedRequest.cache = {};

Of course this assumes you’re using the brand new Prototype 1.6