-
-
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.
This file contains 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
/* | |
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 ); | |
} | |
}); |
This file contains 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
// 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