JS how to cache a variable
Solution 1:
Use localStorage for that. It's persistent over sessions.
Writing :
localStorage['myKey'] = 'somestring'; // only strings
Reading :
var myVar = localStorage['myKey'] || 'defaultValue';
If you need to store complex structures, you might serialize them in JSON. For example :
Reading :
var stored = localStorage['myKey'];
if (stored) myVar = JSON.parse(stored);
else myVar = {a:'test', b: [1, 2, 3]};
Writing :
localStorage['myKey'] = JSON.stringify(myVar);
Note that you may use more than one key. They'll all be retrieved by all pages on the same domain.
Unless you want to be compatible with IE7, you have no reason to use the obsolete and small cookies.
Solution 2:
You have three options:
- Cookies: https://developer.mozilla.org/en-US/docs/DOM/document.cookie
- DOMStorage (sessionStorage or localStorage): https://developer.mozilla.org/en-US/docs/DOM/Storage
- If your users are logged in, you could persist data in your server's DB that is keyed to a user (or group)