Skip to content

Instantly share code, notes, and snippets.

@jaredrada
Last active April 28, 2018 05:04
Show Gist options
  • Select an option

  • Save jaredrada/7185419 to your computer and use it in GitHub Desktop.

Select an option

Save jaredrada/7185419 to your computer and use it in GitHub Desktop.
jquery ajax localstorage cache
$.ajaxPrefilter(function(options, originalOptions, jqXHR){
if(!options.ajaxCache) {
return;
}
var cacheOptions = options.ajaxCache;
var timeToLive = cacheOptions.timeToLive || 1000 * 60 * 60, //1hour
cacheKey = cacheOptions.cacheKey || options.type + options.url,
cached = JSON.parse(localStorage.getItem(cacheKey));
if(
(!cached) //if cache does not exist
|| (cacheOptions.garbageCache) //if user wants new data
|| (cached.created + cached.timeToLive >= new Date().getTime()) //if cache is expired
) {
//then remove the data, do a new ajax request, and store the result
localStorage.removeItem(cacheKey);
jqXHR.done(function(data){
var storageObj = {
timeToLive : timeToLive,
created : new Date().getTime,
data : data
};
localStorage.setItem(cacheKey, JSON.stringify(storageObj));
});
console.log('getting new data');
} else {
//otherwise the data is still good, so return that
//i'd like to manually resolve the deferred object here and create a "200" response code so everything downstream reacts normally
jqXHR.status = 200;
jqXHR.responseJSON = cached.data;
jqXHR.abort(); //this breaks things, see if we can resolve deferred on our own?
console.log('data is good');
console.log(jqXHR);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment