Ajax.CachedRequest
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
Sun 11/11/07, 22:58
The way I always cache AJAX results is inside the actual dom itself as html elements and classnames.
Every time I go to fetch some ajax, i’ll check to make sure the classname is in the uncached state. Once I fetch the ajax result I immediately dump it into the the dom as html elements.
If there was an error that I don’t want to display to the user I use CSS rules to define what is visible when.
I like to keep all visual rules in CSS and all functionality in javascript. I like my javascript as dumb and simple as possible.
I like your technique though. If I ever have a project that requires fetching a lot of data that doesn’t immendiately need to be dumped to the dom, this would be handy.
/
Mon 12/11/07, 00:55
Thomas, using DOM to store cached data could get quite slow in IE (if we’re talking about a lot of data) Using plain old objects for cache keeps all browsers on the edge of perfomance…
/
Mon 12/11/07, 03:59
Well, I only do that for sites that have a 1-1 relationship of Ajax requests to user-facing action. It wouldnt make sense for a site that did a bunch of stuff in the background.
/
Sun 24/2/08, 04:22
I think FF will automatically cache and reuse any http GET, as long as the URL is the same and the headers are correct for caching. I’m not sure about the other browsers, but I think this is standard GET behavior, whether its from an AJAX call or to return a webpage.
/