HTML Web Storage API | Web Workers| HTML SSE

HTML web storage; better than cookies.

What is HTML Web Storage?

With web storage, web applications can store data locally within the user’s browser. Before HTML5, application data had to be stored in cookies, included in every server request. Web storage is more secure, and large amounts of data can be stored locally, without affecting website performance. Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server. Web storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data.

HTML Web Storage Objects

HTML web storage provides two objects for storing data on the client:

  • window.localStorage – stores data with no expiration date
  • window.sessionStorage – stores data for one session (data is lost when the browser tab is closed)

Before using web storage, check browser support for localStorage and sessionStorage:

if (typeof(Storage) !== "undefined") {
  // Code for localStorage/sessionStorage.
} else {
  // Sorry! No Web Storage support..
}

The localStorage Object

The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.

Example

// Store
localStorage.setItem("lastname", "Smith");

// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");

Example explained:

  • Create a localStorage name/value pair with name=”lastname” and value=”Smith”
  • Retrieve the value of “lastname” and insert it into the element with id=”result”

The example above could also be written like this:

// Store
localStorage.lastname = "Smith";
// Retrieve
document.getElementById("result").innerHTML = localStorage.lastname;

The syntax for removing the “lastname” localStorage item is as follows:

localStorage.removeItem("lastname");

The following example counts the number of times a user has clicked a button. In this code the value string is converted to a number to be able to increase the counter:

Example

if (localStorage.clickcount) {
  localStorage.clickcount = Number(localStorage.clickcount) + 1;
} else {
  localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
localStorage.clickcount + " time(s).";

The sessionStorage Object

The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the specific browser tab. The following example counts the number of times a user has clicked a button, in the current session:

Example

if (sessionStorage.clickcount) {
  sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
  sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";

HTML Web Workers API

A web worker is a JavaScript running in the background, without affecting the performance of the page.

What is a Web Worker?

When executing scripts in an HTML page, the page becomes unresponsive until the script is finished. A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.

HTML Web Workers Example

The example below creates a simple web worker that count numbers in the background:

Example

Count numbers:

Start Worker  Stop Worker

Check Web Worker Support

Before creating a web worker, check whether the user’s browser supports it:

if (typeof(Worker) !== "undefined") {
  // Yes! Web worker support!
  // Some code.....
} else {
  // Sorry! No Web Worker support..
}
ADVERTISEMENT

Create a Web Worker File

Now, let’s create our web worker in an external JavaScript. Here, we create a script that counts. The script is stored in the “demo_workers.js” file:

var i = 0;

function timedCount() {
  i = i + 1;
  postMessage(i);
  setTimeout("timedCount()",500);
}

timedCount();

Create a Web Worker Object

Now that we have the web worker file, we need to call it from an HTML page. The following lines checks if the worker already exists, if not – it creates a new web worker object and runs the code in “demo_workers.js”:

if (typeof(w) == "undefined") {
  w = new Worker("demo_workers.js");
}

Terminate a Web Worker

When a web worker object is created, it will continue to listen for messages (even after the external script is finished) until it is terminated. To terminate a web worker, and free browser/computer resources, use the terminate() method:

w.terminate();

Reuse the Web Worker

If you set the worker variable to undefined, after it has been terminated, you can reuse the code:

w = undefined;

Full Web Worker Example Code

We have already seen the Worker code in the .js file. Below is the code for the HTML page:

Example

<!DOCTYPE html>
<html>
<body>

<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button>
<button onclick="stopWorker()">Stop Worker</button>

<script>
var w;

function startWorker() {
  if (typeof(Worker) !== "undefined") {
    if (typeof(w) == "undefined") {
      w = new Worker("demo_workers.js");
    }
    w.onmessage = function(event) {
      document.getElementById("result").innerHTML = event.data;
    };
  } else {
    document.getElementById("result").innerHTML = "Sorry! No Web Worker support.";
  }
}

function stopWorker() {
  w.terminate();
  w = undefined;
}
</script>

</body>
</html>

Web Workers and the DOM

Since web workers are in external files, they do not have access to the following JavaScript objects:

  • The window object
  • The document object
  • The parent object

HTML SSE API

Server-Sent Events (SSE) allow a web page to get updates from a server.

Server-Sent Events – One Way Messaging

A server-sent event is when a web page automatically gets updates from a server This was also possible before, but the web page would have to ask if any updates were available. With server-sent events, the updates come automatically. Examples: Facebook/Twitter updates, stock price updates, news feeds, sport results, etc.

HTML Web Storage API | Web Workers| HTML SSE
Show Buttons
Hide Buttons