jquery-ajax-localstorage-cache - abbreviated Jalc from here on, because the full name is a mouthful.
Jalc is a plugin built for jQuery (>= 1.5.1 for 1.x.x, and >=3.0.0 for 2.x.x) and any object implementing the storage interface, such as localStorage, providing a client-side cache for AJAX responses intended to save bandwith and time.
Versions tagged 1.x.x support jQuery 1.5.1+ up to jQuery version 3.0.0. Version 1.x.x is no longer receiving any updates, except bug fixes as needed.
Versions tagged 2.x.x support jQuery 3.0.0+.
You can download and install this plugin using bower:
bower install jalc
You can also download the minified distribution version and install manually in your application: jalc.min.js.
$.ajax({
url: '/post',
localCache: true, // Required. Either a boolean, in which case localStorage will be used, or
// an object that implements the Storage interface.
cacheTTL: 1, // Optional. In hours. Can be used with float to indicate part of an hour, e.g. 0.5.
cacheKey: 'post', // optional.
isCacheValid: function () { // optional.
return true;
},
isResponseValid: function (data, status, jqXHR) { // optional.
return data.code === '0';
},
thenResponse: function (data, status, jqXHR) { // optional, only in versions 2.x.x+
// Alter data in whatever way you want it altered before it gets cached.
data.code = 101;
return data;
}
}).done(function (response) {
// The response is available here.
});
On your AJAX request you get 6 new parameters :
0.5
to indicate half-an-hour.then
or done
block. Allows you to specify
a function which will alter the data in some way before caching it and returning it. Keep in mind that this
function will NOT be called when fetching from the cache, only when fetching from remote, so don't rely on it
to perform a transformation that you want to occur every time you make the ajax call - those should instead go
in a then
block on your ajax
request.localStorage.clear()
, or by using localStorage.removeItem('cacheKey')
if you specified a cacheKey. Note the above assumes you're using localStorage - replace as appropriate with your
Storage interface implementing object.dataType
parameter,
and the plugin will store the content type returned from the server alongside the data. However, you will
get more consistent results if you explicitly specify the dataType in the ajax parameters.This project is distributed under Apache 2 License. See LICENSE.txt for more information.