Skip to content

Instantly share code, notes, and snippets.

@gemmadlou
Forked from contolini/getCache.js
Created June 18, 2016 09:04
Show Gist options
  • Save gemmadlou/bb920a8d98d4bef0c3d907221297dadc to your computer and use it in GitHub Desktop.
Save gemmadlou/bb920a8d98d4bef0c3d907221297dadc 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment