Skip to content

Instantly share code, notes, and snippets.

@contolini
Forked from ryanflorence/getCache.js
Last active January 17, 2020 14:58
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save contolini/6115380 to your computer and use it in GitHub Desktop.
Save contolini/6115380 to your computer and use it in GitHub Desktop.
Memoization of jQuery's $.getJSON() to use localStorage for caching.
var getCache = function(url) {
var supportsLocalStorage = 'localStorage' in window;
// Both functions return a promise, so no matter which function
// gets called inside getCache, you get the same API.
function getJSON(url) {
var promise = $.getJSON(url);
promise.done(function(data) {
localStorage.setItem(url, JSON.stringify(data));
});
console.log('%c' + url + ' fetched via AJAX', 'color: orange');
return promise;
}
function getStorage(url) {
var storageDfd = new $.Deferred(),
storedData = localStorage.getItem(url);
if (!storedData) {
return getJSON(url);
}
setTimeout(function() {
storageDfd.resolveWith(null, [JSON.parse(storedData)]);
});
console.log('%c' + url + ' fetched via localStorange', 'color: blue');
return storageDfd.promise();
}
return supportsLocalStorage ? getStorage( url ) : getJSON( url );
};
// Instead of using jQuery's $.getJSON('foo/bar.json'), use getCache('foo/bar.json').
// first time uses an ajax request
getCache('foo/bar.json').then(function (data) {
console.log(data);
});
// second time pulls from local storage
getCache('foo/bar.json').then(function (data) {
console.log(data);
});
// always executes in asynchronous order, uses ajax always if localStorage isn't supported.
@gemmadlou
Copy link

gemmadlou commented Jun 18, 2016

I have to try this. Thanks for the gist.


...just tried. It works great! I'm using it here:
https://jsfiddle.net/gemmadlou/fez69ggg/

I've left your console.logs on - thanks again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment