Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created November 7, 2011 18:44
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ryanflorence/1345787 to your computer and use it in GitHub Desktop.
Save ryanflorence/1345787 to your computer and use it in GitHub Desktop.
Cache data in the localStorage
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;
}());
// 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.
@ScottRadcliff
Copy link

I haven't tried running this code, but curious if it prompts the user for permission to store data on their machine?

@ryanflorence
Copy link
Author

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