[javascript] 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.

This question is related to javascript jquery html

The answer is


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.


check out my js lib for caching: https://github.com/hoangnd25/cacheJS

My blog post: New way to cache your data with Javascript

Features:

  • Conveniently use array as key for saving cache
  • Support array and localStorage
  • Clear cache by context (clear all blog posts with authorId="abc")
  • No dependency

Basic usage:

Saving cache:

cacheJS.set({blogId:1,type:'view'},'<h1>Blog 1</h1>');
cacheJS.set({blogId:2,type:'view'},'<h1>Blog 2</h1>', null, {author:'hoangnd'});
cacheJS.set({blogId:3,type:'view'},'<h1>Blog 3</h1>', 3600, {author:'hoangnd',categoryId:2});

Retrieving cache:

cacheJS.get({blogId: 1,type: 'view'});

Flushing cache

cacheJS.removeByKey({blogId: 1,type: 'view'});
cacheJS.removeByKey({blogId: 2,type: 'view'});

cacheJS.removeByContext({author:'hoangnd'});

Switching provider

cacheJS.use('array');
cacheJS.use('array').set({blogId:1},'<h1>Blog 1</h1>')};

You have three options:

  1. Cookies: https://developer.mozilla.org/en-US/docs/DOM/document.cookie
  2. DOMStorage (sessionStorage or localStorage): https://developer.mozilla.org/en-US/docs/DOM/Storage
  3. If your users are logged in, you could persist data in your server's DB that is keyed to a user (or group)

You could possibly create a cookie if thats allowed in your requirment. If you choose to take the cookie route then the solution could be as follows. Also the benefit with cookie is after the user closes the Browser and Re-opens, if the cookie has not been deleted the value will be persisted.

Cookie *Create and Store a Cookie:*

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

The function which will return the specified cookie:

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

Display a welcome message if the cookie is set

function checkCookie()
{
var username=getCookie("username");
  if (username!=null && username!="")
  {
  alert("Welcome again " + username);
  }
else 
  {
  username=prompt("Please enter your name:","");
  if (username!=null && username!="")
    {
    setCookie("username",username,365);
    }
  }
}

The above solution is saving the value through cookies. Its a pretty standard way without storing the value on the server side.

Jquery

Set a value to the session storage.

Javascript:

$.sessionStorage( 'foo', {data:'bar'} );

Retrieve the value:

$.sessionStorage( 'foo', {data:'bar'} );

$.sessionStorage( 'foo' );Results:
{data:'bar'}

Local Storage Now lets take a look at Local storage. Lets say for example you have an array of variables that you are wanting to persist. You could do as follows:

var names=[];
names[0]=prompt("New name?");
localStorage['names']=JSON.stringify(names);

//...
var storedNames=JSON.parse(localStorage['names']);

Server Side Example using ASP.NET

Adding to Sesion

Session["FirstName"] = FirstNameTextBox.Text;
Session["LastName"] = LastNameTextBox.Text;

// When retrieving an object from session state, cast it to // the appropriate type.

ArrayList stockPicks = (ArrayList)Session["StockPicks"];

// Write the modified stock picks list back to session state.
Session["StockPicks"] = stockPicks;

I hope that answered your question.


I have written a generic caching func() which will cache any variable easily and very readable format. Caching function:

function calculateSomethingMaybe(args){
  return args;
}

function caching(fn){
  const cache = {};
  return function(){
    const string = arguments[0];
    if(!cache[string]){
      const result = fn.apply(this, arguments);
      cache[string] = result;
      return result;
    }
    return cache[string];
  }
}

const letsCache = caching(calculateSomethingMaybe);

console.log(letsCache('a book'), letsCache('a pen'), letsCache('a book'));

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment