Thursday, June 6, 2013

Caching with javascript and HTML5 local storage


As I said in my last post, I've started working on another finance tool. While I haven't made much progress on the actual implementation of accounts and all that, I have started creating a core system to speed up the system for efficiency.

I am creating my own Javascript library to cache the results of a request to certain URLs. What happens at the core of this, is thus:

If we haven not yet cached the url we submit our AJAX request to the server, if we have cached the result, we return that instead. Sounds like a pretty simple concept to me. And it turns out, with a little bit of work it's not too hard to implement.

http://pastebin.com/drrqi8Pw

Instead of crudely pasting the code into this post, I've included it in the paste above. while this code will not run if you just plug it into a file (local dependencies on the library I'm making), you can get the general idea of how it works.

A use case can go something like this:
The user calls some function out of the library (such as getBudget) which, after making sure parameters are correctly, sends the url and a requestHandler to the apiRequest function. The url is parsed into just the important parameters and checked against the cache. If it's in the cache that object will be passed as an argument to the users requestHandler, if not, then we'll make the ajax request. Assuming we've made the ajax request, during the respond we'll pass the response JSON to the user's function first, and then we'll perform whatever operations we need in order to store it locally and mark the url we used to get it as cache-able.

You'll notice that I've included the apiSendDate in the paste as well, this is because we need to map CRUD operations (minus the R) to URLs that retrieve that data. This is abstracted away into the apiURLMap object, which (if the finance tool becomes complicated --which it will) will eventually become a function in order to map a single URL to multiple url's that would correspond to stale information.

To prove to you that this works (since I provided non-functioning code above) here's a couple screenshots of my mock prototype --please keep in mind front end is not important to me until the functionality is there--

Network traffic for first submission

S



Submitting a request by clicking the Get Items link



Submitting a second request, uses the cache





Second shot of the network requests, only the first one is there, so we've saved ourselves the trip to the server


Note: Just to let everyone know, localStorage can only store strings by default unless you override the eprototypes, that's why we stringify the data before placing it into the local storage

No comments:

Post a Comment