-
-
Save contolini/6115380 to your computer and use it in GitHub Desktop.
Memoization of jQuery's $.getJSON() to use localStorage for caching.
This file contains hidden or 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
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 ); | |
}; |
This file contains hidden or 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 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
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.