AJAX - The Complete Reference

(avery) #1

PART II


Chapter 6: Networking Considerations 273


NOT EOTE To set cache policy on a Web server you may need to use mod_headers on Apache or
CacheRight on IIS.

An Ajax Response Cache


While the browser cache can work, there are situations where you might want to cache and
the browser won’t do it automatically. For example, browsers will not cache POST requests
no matter what, so if you know that a POST value should be cached for some reason, you’ll
have to do that manually. In order to provide maximum flexibility, it would be useful to
implement a client-side cache to store Ajax response values for reuse.
The AjaxTCR library supports an Ajax request cache so you can explore just how useful
such a facility can be. To enable caching, set cacheResponse to true in your request options.

var options = { method: "GET",
payload: payload,
onSuccess : handleResponse,
cacheResponse : true
};

By default, the library uses a cache of 100 entries, uses a least-recently-used (LRU)
algorithm to decide what items are in cache, and sets a time limit of 60 minutes for an item
to be in cache.

/* The cache object */
_cache : new Array(),

/* Caching Options w/defaults */
_cacheOptions : {

/* The max number of items to store in the cache */
size : 100,
/* The default algorithm for removing items.
The choices are LRU, FIFO, and LFU */

algorithm: "LRU",
/* The default number of minutes an item can stay in the cache.
Set to -1 for forever */
expires: 60
},

As seen in the code fragment, the cache management algorithm can be modified to use a
first-in-first-out (FIFO) scheme or a least frequently used (LFU) scheme. The size and
expiration policy for cached items can also be adjusted. The public method:

AjaxTCR.comm.cache.setOptions({size: number, algorithm : LRU | FIFO | LFU,
expires: number})

is used to set each of these parameters as demonstrated here:

AjaxTCR.comm.cache.setOptions({size:3, algorithm: "LFU", expires:-1});

With caching enabled, as the user calls AjaxTCR.comm.sendRequest(), the library
now needs to check if the item is in the cache or not. To determine if caching is on,
Free download pdf