How to implement cache for Ajax requests

I have a simple application that shows a list of many elements where the user can display the details for each element that Ajax received.

However, if the user closes the details and reopens, the application makes another Ajax request to get the same content again.

Is there any simple solution how to prevent this by caching requests on the client, so when the user displays the same part again, the contents will be loaded from the cache. Preferred to use jQuery .

I think this can be solved using a proxy object that will store the request when it is created for the first time, and when the request is executed again, the proxy server will simply return the previous result without making another Ajax request.

But I'm looking for some simpler solution where I do not have to do it all on my own.

+4
source share
4 answers

Take a look at these jQuery plugins:

JQache example:

// [OPTIONAL] Set the max cached item number, for example 20 $.jCache.maxSize = 20; // Start playing around with it: // Put an item into cache: $.jCache.setItem(theKey, theValue); // Retrieve an item from cache: var theValue = $.jCache.getItem(theKey); // Clear the cache (well, I think most of us don't need this case): $.jCache.clear(); 
+2
source

The easiest way IMHO is to create a global array:

 var desc_cache=[]; 

and then create a function like this:

 function getDesc(item){ if(desc_cache[item]) return desc_cache[item] else $.ajax(...); } 

After receiving ajax data, save the results in desc_cache.

+2
source

Another jQuery cache plugin in which you can set the expiration and object dependencies:

http://plugins.jquery.com/project/jCacher

JCacher code example:

 $(document).ready(function() { $.jCacher.add("key", "value"); }); $(document).ready(function() { var cacheItem = $.jCacher.get("key"); alert(cacheItem.value + " was retrieved from the cache"); }); 
+1
source

You can create one or two classes to encapsulate the fact that you are caching; you can then use AJAX or cache interchangeably. See here: http://myok12.wordpress.com/2011/08/19/building-an-almighty-data-retrieval-system-for-all-html5-webapps/

0
source

All Articles