Created
November 7, 2011 18:44
-
-
Save ryanflorence/1345787 to your computer and use it in GitHub Desktop.
Cache data in the localStorage
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
var getCache = (function() { | |
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(key) { | |
return jQuery.getJSON(key).then(function(data) { | |
localStorage.setItem(key, JSON.stringify(data)); | |
}).promise(); | |
} | |
function getStorage(key) { | |
var storageDfd = new jQuery.Deferred(), | |
storedData = localStorage.getItem(key); | |
if (!storedData) return getJSON(key); | |
setTimeout(function() { | |
storageDfd.resolveWith(null, [JSON.parse(storedData)]); | |
}); | |
return storageDfd.promise(); | |
} | |
return supportsLocalStorage ? getJSON : getStorage; | |
}()); |
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
// first time uses an ajax request | |
getCache('/cache/1234').then(function (data) { | |
console.log(data); | |
}); | |
// second time pulls from local storage | |
getCache('/cache/1234').then(function (data) { | |
console.log(data); | |
}); | |
// always executes in asynchronous order, uses ajax always if localStorage isn't supported. |
I've never heard of that happening--but it would make sense to check for the availability of local storage first.
updated to check for localStorage support
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I haven't tried running this code, but curious if it prompts the user for permission to store data on their machine?