Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS how to cache a variable

What I want to do is to be able to create a variable, give it a value, close and reopen the window, and be able to retrieve the value I set in the last session. What is the simplest way to do that? JQuery answers are welcome.

like image 280
Bluefire Avatar asked Jan 10 '13 20:01

Bluefire


People also ask

How do you cache something in JavaScript?

You can cache a resource using three methods add , addAll , set . add() and addAll() method automatically fetches a resource, and caches it, whereas in set method we will fetch a data and set the cache.

What is caching in JS?

Caching is a common technique for making your applications faster. It lets you avoid slow operations by reusing previous results. In this article, Ayo Isaiah walks us through the different options for caching in NodeJS applications. By Ayooluwa Isaiah.


1 Answers

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.

like image 134
Denys Séguret Avatar answered Oct 05 '22 06:10

Denys Séguret