Skip to content

Instantly share code, notes, and snippets.

@chrisma
Forked from contolini/getCache.js
Last active February 16, 2017 15:27
Show Gist options
  • Save chrisma/6538624c7941e9ba97bed36f395b26d6 to your computer and use it in GitHub Desktop.
Save chrisma/6538624c7941e9ba97bed36f395b26d6 to your computer and use it in GitHub Desktop.
Adaptation of jQuery's $.getJSON() to use localStorage for caching. Supports invalidation after timeout.
/*
Return JSON from url, use browser's localStorage as cache
JQuery extension, returns a promise.
'cacheInvalidMs' indicates the milliseconds after which the cache is invalidated.
Default is 24 hours.
'cacheDelayMs' indicates the milliseconds after which data from the cache is returned.
Can be used to simulate the delay of normal requests.
Default is 0.
*/
//Adapted from https://gist.github.com/contolini/6115380
jQuery.extend({
getCachedJSON: function(url, cacheDelayMs = 0, cacheInvalidMs = 86400000) {
var supportsLocalStorage = 'localStorage' in window;
// Both functions 'getJSON' and 'getCache' return a promise
function getJSON(url) {
var promise = $.getJSON(url);
promise.done(function(data) {
var cache = {data: data, timestamp: new Date().getTime()};
localStorage.setItem(url, JSON.stringify(cache));
});
console.log('%c' + url + ' (AJAX)', 'color: orange');
return promise;
}
function getCache(url) {
var stored = JSON.parse(localStorage.getItem(url));
if ( stored ) {
var validCache = (new Date().getTime() - stored.timestamp) < cacheInvalidMs;
if ( validCache ) {
console.log('%c' + url + ' (localStorange)', 'color: blue');
var dfd = $.Deferred();
if ( cacheDelayMs > 0 ){
setTimeout(function() { dfd.resolve(stored.data); }, cacheDelayMs );
} else {
dfd.resolve(stored.data);
}
return dfd.promise()
}
}
return getJSON(url);
}
return supportsLocalStorage ? getCache( url ) : getJSON( url );
}
});
// Instead of using jQuery's $.getJSON('foo/bar.json'), use $.getCachedJSON('foo/bar.json').
// first time uses an ajax request
$.getCachedJSON('foo/bar.json').done(function (data) {
console.log(data);
});
// second time pulls from local storage
$.getCachedJSON('foo/bar.json').done(function (data) {
console.log(data);
});
// always executes in asynchronous order, uses ajax always if localStorage isn't supported.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment