-
Notifications
You must be signed in to change notification settings - Fork 6
/
jquery-ajax-jstorage-cache.js
56 lines (44 loc) · 1.51 KB
/
jquery-ajax-jstorage-cache.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
(function( $ ) {
var log = function(message) {
if ( window.console ) {
console.debug( message );
}
};
$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
if( options.cacheJStorage === undefined || ! options.cacheJStorage )
return;
var cacheKey;
if ( options.cacheKey )
cacheKey = options.cacheKey;
else
cacheKey = options.url + options.type + options.data;
if ( options.isCacheValid && ! options.isCacheValid() )
$.jStorage.deleteKey( cacheKey );
if ( $.jStorage.get( cacheKey ) ) {
// Do not send a direct copy of Data
var dataCached = $.extend(true, {}, $.jStorage.get( cacheKey ));
if ( options.success )
options.success( dataCached );
// Abort is broken on JQ 1.5
jqXHR.abort();
}
else {
var successhandler = options.success,
cacheTTL = options.cacheTTL || 0;
options.success = function( data ) {
$.jStorage.set( cacheKey, data );
if ( $.jStorage.setTTL ) {
$.jStorage.setTTL( cacheKey, cacheTTL * 1000 );
}
else
log('Your jStorage version doesn\'t support TTL on key, please update jStorage ( http://www.jstorage.info/ )');
// Send a deep clone of data
var dataCached = $.extend(true, {}, data );
if ( successhandler )
successhandler( dataCached );
// Don't execute this success callback again
options.success = successhandler;
};
}
});
})( jQuery );