Skip to content

Instantly share code, notes, and snippets.

@blestab
Forked from k0pernikus/getCachedJSON.js
Created April 15, 2017 16:23
Show Gist options
  • Save blestab/feefc5b12c49b9d0e60ad96114a85659 to your computer and use it in GitHub Desktop.
Save blestab/feefc5b12c49b9d0e60ad96114a85659 to your computer and use it in GitHub Desktop.
jQuery.getJSON abstraction to cache data to localStorage with invalidation option based time
jQuery.extend({
getCachedJSON: function (url, callback) {
var cacheTimeInMs = 3600000;
var currentTimeInMs = new Date().getTime();
var cache = {
data:null,
timestamp:null
};
if (typeof window.localStorage[url] !== "undefined") {
cache = JSON.parse(window.localStorage[url]);
var validCache = (currentTimeInMs - cache.timestamp) < cacheTimeInMs;
if (validCache) {
callback(cache.data);
return true;
}
}
$.getJSON(url, function (data) {
cache.data = data;
cache.timestamp = new Date().getTime();
window.localStorage[url] = JSON.stringify(cache);
callback(cache.data);
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment