Update : We are aware that in most case you should use the browser built-in mechanisms, but in realtime applications like Fresc you may want to be able to read, update, or delete your cached data when some events occurs.
Each time we talk about caching, we usually think about client side ressources, SQL requests and fragment caching. But, does it cover everything ?
On Fresc most of the navigation is done via AJAX. For example images switching is a JSON containing url, name and many others metadatas. We noticed that each time a client was requesting again the same image, it was the same response over and over.
Why keep requesting for something already known ? That's why we developed a mechanism to cache responses from Ajax Request, allowing you to avoid making unnecessary requests in order to save time and bandwidth. We bundled this in a jQuery plugin named jquery-ajax-jstorage-cache
How to cache AJAX requests with jQuery
The plugin is a jQuery.ajax prefilter. Since HTML5 allow us to use LocalStorage, we use this space as the cache storage. To manipulate it we use a library called jStorage, which allow us to support a large panel of browsers.
Before each requests, the plugin checks if the requests are already cached, and if so, returns the cached version directly and ends up the request.
Caching AJAX requests can be used in many ways like instant pagination, preload data or even fragment page caching.
Here is a snippet of a Rails application to show you how the stuff works. In this case news are displayed via AJAX and cached for later viewing. Note that this sample is a bit too simple to justify using this method instead of classic HTTP caching.
index action renders the layout and provide the last news
An AJAX request is then made to
last_news action get the last 5 news. The
id is used as a key to validate the cache.
On first visit, response will be cached. Then each time index is visited and cached
id matches index's one, no Ajax Request will be triggered.
Use it, Improve it and Fork it
The plugin is available on our Github repository, feel free to fork it and improve it !