Last active
August 29, 2015 14:05
-
-
Save sTiLL-iLL/b7518622c89e1c177556 to your computer and use it in GitHub Desktop.
Simple caching inside of session storage...
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
// 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