Skip to content

Instantly share code, notes, and snippets.

@sTiLL-iLL
Last active August 29, 2015 14:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sTiLL-iLL/b7518622c89e1c177556 to your computer and use it in GitHub Desktop.
Save sTiLL-iLL/b7518622c89e1c177556 to your computer and use it in GitHub Desktop.
Simple caching inside of session storage...
// session storage caching
define(function() {
var cacheObj = window.sessionStorage || {
getItem: function(key) {
return this[key];
},
setItem: function(key, value) {
this[key] = value;
}
};
return {
get: function(key) {
return this.isFresh(key);
},
set: function(key, value, minutes) {
var expDate = new Date();
expDate.setMinutes(expDate.getMinutes() + (minutes || 0));
try {
cacheObj.setItem(key, JSON.stringify({
value: value,
expires: expDate.getTime()
}));
}
catch(e) { }
},
isFresh: function(key) {
// value or false
var item;
try {
item = JSON.parse(cacheObj.getItem(key));
}
catch(e) {}
if(!item) return false;
return new Date().getTime() > item.expires ? false : item.value;
}
}
});
// Use it
require(['storage'], function(storage) {
var content = storage.get('sidebarContent');
if(!content) {
// request to get content & store for 1 hr
storage.set('sidebarContent', content, 60);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment