Created
November 20, 2011 04:42
-
-
Save ryanflorence/1379804 to your computer and use it in GitHub Desktop.
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() { | |
| var supportsLocalStorage = 'localStorage' in window, | |
| cache = {}; | |
| function getJSON(key) { | |
| return jQuery.getJSON(key).then(function(data) { | |
| cache[key] = data; | |
| localStorage.setItem(key, JSON.stringify(data)); | |
| }).promise(); | |
| } | |
| function getStorage(key) { | |
| var storedData = localStorage.getItem(key); | |
| return storedData ? finish(JSON.parse(storedData)) : getJSON(key); | |
| } | |
| function finish(data) { | |
| var dfd = new jQuery.Deferred(); | |
| setTimeout(function() { | |
| dfd.resolveWith(null, [data]); | |
| }); | |
| return dfd.promise(); | |
| } | |
| return function(key) { | |
| if (cache[key]) finish(key); | |
| return supportsLocalStorage ? getStorage(key) : getJSON(key); | |
| }; | |
| }()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment