Improving web application performance by using session storage with JavaScript

Written by Paul Bradley

Improving web performance by caching expensive AJAX results into session.Storage

midjourney ai - fantasy cheetah running, with crystal ears and tail

Table of Contents
  1. Introduction
  2. sessionStorage.getItem
  3. sessionStorage.setItem
  4. sessionStorage.removeItem
  5. Need Help or Advice

Introduction

In my day job, I work on a web application that consolidates clinical information from multiple sources. One of those sources is a Health Information Exchange. Depending on the patient, it can take several seconds to return the data for a patient with a complex medical history.

As such, the data is returned via an AJAX request so that I can present the user with a progress bar while the health information exchange responds. This article demonstrates how I use sessionStorage to cache the results and make the web application feel more responsive to the user.

The Web Storage API provides mechanisms by which browsers can store key/value pairs in a much more intuitive fashion than using cookies. The Web Storage API provides two mechanisms for caching data, localStorage and sessionStorage.

The localStorage API persists data even when the browser is closed and reopened. It stores data with no expiration date and gets cleared only through JavaScript or clearing the browser cache. As my web application holds clinical data, I didn’t want to cache that data between browsing sessions.

As such, I choose sessionStorage as it maintains a separate storage area for each given origin. It stores data only for a session, meaning that the information is only stored until the browser (or tab) is closed. The data is never transferred to the server. It also has a much larger storage limit than a cookie, allowing up to 5MB of data to be stored.

sessionStorage.getItem

First, we need to use getItem function to see if anything is already stored in the cache. The getItem function has one parameter, the key name, a string containing the name of the key you want to retrieve.

If the cache is empty, we perform the AJAX request by checking if it equals null. If the cache isn’t empty, we load the HTML code from the cache by using the getItem function and assign it the HTML element with an id attribute of LloyedGeorge.

Lloyed George was the person known for inventing the paper patient records and as this is a medical application the use of his name as a variable is a hat tip to the man. The placeholder {{.Patient.LloyedGeorge}} in the sample below is replaced with a unique value for each patient. This ensures that if a user is viewing multiple patient records, the cached data for another patient isn’t retrieved and displayed incorrectly.

It’s a good idea to use a unique key name that has a meaning within your application.

1if (sessionStorage.getItem("{{.Patient.LloyedGeorge}}") === null) {
2    xds_ajax_request();
3} else {
4    document.getElementById("LloyedGeorge").innerHTML = sessionStorage.getItem("{{.Patient.LloyedGeorge}}");
5}

sessionStorage.setItem

When our AJAX call responds with a valid result, we assign responseText to the HTML element with an id attribute of LloyedGeorge.

We also save a copy of the responseText into the session storage using the setItem function call. The setItem function accepts two parameters. The first is a key name, a string containing the name of the key you want to create/update. The second is the key value, a string containing the value you want to give the key you are creating or updating.

Once we’ve saved the AJAX response into the session storage, we can refresh the web page, and the AJAX call won’t be triggered, as the code example above will load the data directly from the session storage. Again, this makes your application feel fast, as the data will appear immediately.

1if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
2    document.getElementById("LloyedGeorge").innerHTML = xmlHttp.responseText;
3    sessionStorage.setItem("{{.Patient.LloyedGeorge}}", xmlHttp.responseText);
4}

sessionStorage.removeItem

If you decide to use the sessionStorage API’s, you need a way for your users to invalidate the cache, so your application can re-query the AJAX endpoint/service. On a mobile application, this might be a pull to refresh gesture, or it could be a button the user needs to press. Either way, the refresh event should call the removeItem function to invalidate the cache.

The removeItem function has one parameter: the key name for the key you want to remove.

1function force_refresh() {
2    sessionStorage.removeItem('{{.Patient.LloyedGeorge}}');
3}

Need Help or Advice

If you need help or advice on improving your web application performance, don’t hesitate to get in touch with me via Twitter. Send me a direct message to @nhsdeveloper.