Improving web application performance by using session storage with JavaScript
Tags: webdev, frontend, javascript
Published: 2022-09-14 10:21:30

---
title: Improving web application performance by using session storage with JavaScript
published: true
description: Improving the perceived performance of your web applications by caching expensive AJAX results into session.Storage
tags: #webdev, #frontend, #javascript
canonical_url: https://paulbradley.dev/javascript-session-storage/
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wmc1wppppokfomiy9zxt.png
---

## Introduction

In my day job, I work on a web application that consolidates <a rel="noopener" href="https://aws.amazon.com/blogs/publicsector/breaking-down-patient-data-silos-uk-healthcare-serverless-cloud-technology/" target="_blank">clinical information from multiple sources</a>. One of those sources is a [Health Information Exchange](https://www.ihe.net/). 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](https://developer.mozilla.org/en-US/docs/Web/API/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](https://en.wikipedia.org/wiki/David_Lloyd_George) was the person known for inventing the [paper patient records](https://pcse.england.nhs.uk/help/gp-record-movement/lloyd-george-envelopes-for-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.

```javascript
if (sessionStorage.getItem(".Patient.LloyedGeorge") === null) {
    xds_ajax_request();
} else {
    document.getElementById("LloyedGeorge").innerHTML = sessionStorage.getItem(".Patient.LloyedGeorge");
}
```

## 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.

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

## 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](https://en.wikipedia.org/wiki/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.

```javascript
function force_refresh() {
    sessionStorage.removeItem('.Patient.LloyedGeorge');
}
```

## 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 <a rel="noopener" href="https://twitter.com/nhsdeveloper">@nhsdeveloper</a>.