Performance Zone is brought to you in partnership with:

John regularly blogs about ColdFusion, JavaScript and other web technologies and contributes to several FOSS projects. His hobbies include writing in the third person. John is a DZone MVB and is not an employee of DZone and has posted 32 posts at DZone. You can read more from them at their website. View Full User Profile

Caching AJAX data locally with AmplifyJS

07.30.2013
| 2204 views |
  • submit to reddit

I've been working on a project (www.footyformation.com) where quite a lot of data is loaded in via AJAX. The data doesn't change that often so it made sense to use localstorage to cache the data locally. Unfortunately, localstorage isn't available on older browsers, so I thought I'd need to roll my own solution that would detect if localstorage was available and if not then just store the data in memory. It seemed like a common enough problem that someone would already have solved and sure enough they have!

AmplifyJS is a lightweight (8kb) JavaScript library from appendTo() which has three main components; Request, Store and Pub/Sub. The part I've used is the amplify.store. amplify.store is a method that allows you to get and set locally stored data. AmplifyJS takes care of detecting the browser capabilities and using the appropriate storage mechanism that is supported.

My original code looked something like this:

// load teams
function loadTeams(){
  // load from server
  $.ajax({
    url: 'index.cfm?action=ajax.teams',
    dataType: 'json',
    data: {}
  })
  .done(function (data, textStatus, jqXHR) {
    populateTeams(data);
  })
  .fail(function (jqXHR, exception) { 
  })
  .always(function () {
  });
}

To start using AmplifyJS for storing the data with local storage I ended up with something like this:

// load teams
function loadTeams(){
  // try and get the teams from localStorage
  var teams = amplify.store('teams');

  if(typeof teams != 'undefined'){
    // use local data from amplify
    populateTeams(teams);
  }else{
    // load from server
    $.ajax({
      url: 'index.cfm?action=ajax.teams',
      dataType: 'json',
      data: {}
    })
    .done(function (data, textStatus, jqXHR) {
      // update the cache
      amplify.store('teams', data);      
      populateTeams(data);
    })
    .fail(function (jqXHR, exception) { 
    })
    .always(function () {});
  }
}

As you can see I try and load the data via amplify, if it's undefined I get it via AJAX and then store it locally. A pretty simple way to improve the performance of my application.

It's probably worth mentioning that AmplifyJS does have a request method which handles AJAX and caching. As I was adding it to an existing application I chose to just use the store.

Published at DZone with permission of John Whish, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)