Using LocalStorage for client side caching

I have a need to get a list of all production devices and place them on a map. This data takes about 12 – 16 seconds to load. This means that if a user wants to view the map on page load they are out of luck for a few seconds. So what I do is allow the wait to happen once and then cache the data in local storage. This data is updated every 5 minutes. This allows the user to have at least the last fetch of data locally and will display a map right away.

Here is my angular service for doing this:

//Angular service that gets a list of devices
dashboardApp.service('deviceService', function() {
    //Set self to this so we dont lose scope
    var self = this;
    self.devices = new Array();
    //Go and get the latest device list - Takes a long time!!!!
    this.promise = $.getJSON('devicelist');
    //Since the last call takes a long time, I toss it in local storage and grab the cached version from there until the new list comes in.
    if (localStorage.getItem("devicelist")) {
        //I store json as text and need to parse it to make it a JS object
        self.devices = JSON.parse(localStorage.getItem("devicelist"));
    //When the promise (ajax call) is comeplte then write the data to local storage for next time and set the var to the new list
    $.when(this.promise).then(function(data) {
        self.devices = data;
        localStorage.setItem("devicelist", JSON.stringify(data));
    //Repeat every 5 minutes.
    setInterval(function() {
        $.getJSON('devicelist', function(data) {
            self.devices = data;
            localStorage.setItem("devicelist", JSON.stringify(data));
    }, 300000)
Tagged , , ,

2 thoughts on “Using LocalStorage for client side caching

  1. Cool article.. Just a minor typo, the second to ladt line, 300000 should be 30000 if we want 30 seconds as indicated in the comment 🙂

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: