forked from SaneMethod/jquery-ajax-localstorage-cache
-
Notifications
You must be signed in to change notification settings - Fork 1
/
jquery-ajax-localstorage-cache.js
53 lines (44 loc) · 1.81 KB
/
jquery-ajax-localstorage-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
// github.com/paulirish/jquery-ajax-localstorage-cache
// dependent on Modernizr's localStorage test
$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
// Cache it ?
if ( !Modernizr.localstorage || !options.localCache ) return;
var secttl = options.cacheTTL || 5*60*60;
var cacheKey = options.cacheKey ||
options.url.replace( /jQuery.*/,'' ) + options.type + options.data;
// isCacheValid is a function to validate cache
if ( options.isCacheValid && ! options.isCacheValid() ){
localStorage.removeItem( cacheKey );
}
// if there's a TTL that's expired, flush this item
var ttl = localStorage.getItem(cacheKey + 'cachettl');
if ( ttl && ttl < +new Date() ){
localStorage.removeItem( cacheKey );
localStorage.removeItem( cacheKey + 'cachettl' );
ttl = 'expired';
}
var value = localStorage.getItem( cacheKey );
if ( value ){
//In the cache? So get it, apply success callback & abort the XHR request
// parse back to JSON if we can.
if ( options.dataType.indexOf( 'json' ) === 0 ) value = JSON.parse( value );
options.success( value );
// Abort is broken on JQ 1.5 :(
jqXHR.abort();
} else {
//If it not in the cache, we change the success callback, just put data on localstorage and after that apply the initial callback
if ( options.success ) {
options.realsuccess = options.success;
}
options.success = function( data ) {
var strdata = data;
if ( this.dataType.indexOf( 'json' ) === 0 ) strdata = JSON.stringify( data );
localStorage.setItem( cacheKey, strdata );
if ( options.realsuccess ) options.realsuccess( data );
};
// store timestamp
if ( ! ttl || ttl === 'expired' ) {
localStorage.setItem( cacheKey + 'cachettl', +new Date() + 1000 * secttl );
}
}
});