Last active
May 3, 2019 13:01
-
-
Save SaneMethod/5861822 to your computer and use it in GitHub Desktop.
Ajax prefilter for caching, based on paul irish's work at https://github.com/paulirish/jquery-ajax-localstorage-cache, made to work with jqXHR Deferred Promises when paired with an appropriate ajaxTransport.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Prefilter for caching ajax calls - adapted from | |
* https://github.com/paulirish/jquery-ajax-localstorage-cache, made to work with jqXHR Deferred Promises. | |
* See also $.ajaxTransport. | |
* New parameters available on the ajax call: | |
* localCache : true, // required if we want to use the cache functionality | |
* cacheTTL : 1, // in hours. Optional | |
* cacheKey : 'post', // optional | |
* isCacheValid : function // optional - return true for valid, false for invalid | |
* @method $.ajaxPrefilter | |
* @param options {Object} Options for the ajax call, modified with ajax standard settings | |
*/ | |
$.ajaxPrefilter(function(options){ | |
if (!storage || !options.localCache) return; | |
var hourstl = options.cacheTTL || 5; | |
var cacheKey = options.cacheKey || | |
options.url.replace( /jQuery.*/,'' ) + options.type + options.data; | |
// isCacheValid is a function to validate cache | |
if ( options.isCacheValid && !options.isCacheValid() ){ | |
storage.removeItem( cacheKey ); | |
} | |
// if there's a TTL that's expired, flush this item | |
var ttl = storage.getItem(cacheKey + 'cachettl'); | |
if ( ttl && ttl < +new Date() ){ | |
storage.removeItem( cacheKey ); | |
storage.removeItem( cacheKey + 'cachettl' ); | |
ttl = 'expired'; | |
} | |
var value = storage.getItem( cacheKey ); | |
if ( !value ){ | |
// If it not in the cache, we store the data, add success callback - normal callback will proceed | |
if ( options.success ) { | |
options.realsuccess = options.success; | |
} | |
options.success = function( data ) { | |
var strdata = data; | |
if ( this.dataType.indexOf( 'json' ) === 0 ) strdata = JSON.stringify( data ); | |
// Save the data to storage catching exceptions (possibly QUOTA_EXCEEDED_ERR) | |
try { | |
storage.setItem( cacheKey, strdata ); | |
} catch (e) { | |
// Remove any incomplete data that may have been saved before the exception was caught | |
storage.removeItem( cacheKey ); | |
storage.removeItem( cacheKey + 'cachettl' ); | |
console.log('Cache Error:'+e, cacheKey, strdata ); | |
} | |
if ( options.realsuccess ) options.realsuccess( data ); | |
}; | |
// store timestamp | |
if ( ! ttl || ttl === 'expired' ) { | |
storage.setItem( cacheKey + 'cachettl', +new Date() + 1000 * 60 * 60 * hourstl ); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment