Skip to content

Instantly share code, notes, and snippets.

@mstorino
Last active October 14, 2017 18:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mstorino/1fd28b8b9a438bf2406313c4f8ef8fb9 to your computer and use it in GitHub Desktop.
Save mstorino/1fd28b8b9a438bf2406313c4f8ef8fb9 to your computer and use it in GitHub Desktop.
Local Storage

Local Storage

Data persistence. New-ish, not fully supported across browsers. So cookies are used more despite the fact that they are clunky and harder to use.

There are two categories:

Client Side

Local Computer, takes data and creates an object stored in browser so when you refresh page you can pull it down. Public to end user.

Question: Why is this different than caching?

PROS: CONS: Doesn't work across multiple browsers / devices, never use for secure / incrypeted information,

Server Side

Database (API/AJAX mechanism)

PROS: Independent of device, better for secure / incrypted information CONS:

Example script

<script>

// When users click "save-name"
$("#save-name").on("click", function(event) {
  // This line prevents the page from refreshing when a user hits "enter".
  event.preventDefault();

  // Clear the HTML from the greeting header
  $("#greeting").html();

  // Grab the user input
  var username = $("#your-name").val().trim();

  // Clear absolutely everything stored in localStorage using localStorage.clear()
  localStorage.clear();

  // Store the username into localStorage using "localStorage.setItem"
  localStorage.setItem("name", username);

  // And display that name for the user using "localStorage.getItem"
  $("#greeting").html(localStorage.getItem("name"));

});

// By default (upon load) show the name stored in localStorage using "localStorage.getItem"
// Displaying persistent user data
$("#greeting").html(localStorage.getItem("name"));

</script>

localStorage

localStorage is part of javascript object – it exists as part of the structure (you don't need to create this object).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment