Created
December 6, 2011 07:31
-
-
Save aaronsnoswell/1437203 to your computer and use it in GitHub Desktop.
Easy localStorage caching
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
/** | |
* Stores the given key, value pair in localStorage, if it is available | |
*/ | |
function setLocalStorageValue(key, value) { | |
if (window.localStorage) { | |
try { | |
localStorage.setItem(key, value); | |
} catch (e) { | |
// For some reason we couldn't save the value :( | |
console.log("ERROR | Unable to save to localStorage!", key, value, e); | |
} | |
} | |
} | |
/** | |
* Gets a value from localStorage | |
* Returns the default if localStorage is unavailable, or there is no | |
* stored value for that key | |
*/ | |
function getLocalStorageValue(key, def) { | |
if (window.localStorage) { | |
var value = localStorage.getItem(key); | |
if((value == null) || (value == "undefined")) { | |
/* We had a bit of trouble reading the value assumedly | |
* Regardless, try save the value for next time | |
*/ | |
setLocalStorageValue(key, def); | |
value = def; | |
} | |
// Try to (intelligently) cast the item to a number, if applicable | |
if(!isNaN(value*1)) value = value*1; | |
return value; | |
} | |
// If localStorage isn't available, return the default | |
return def; | |
} | |
/** | |
* Clears the given key's value from localStorgage | |
*/ | |
function clearLocalStorageValue(key) { | |
if (window.localStorage) { | |
try { | |
localStorage.removeItem(key); | |
} catch (e) { | |
// For some reason we couldn't clear the value :S | |
console.log("ERROR | Unable to clear localStorage value!", key, e); | |
} | |
} | |
} |
Added Number casting to getLocalStorageValue
Fixed typo.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fixed Modernizr dependancy. Not sure how I missed that :/