Tuesday, February 7, 2012

Javascript Cache or Piggy-backing your browser?

This article demonstrates how any particular set of data can be preserved across various screens without creating heavy server objects like session or request. So basically it does not need a server for preserving form values, xhr response, global variables which may be needed across pages.

So how do we achieve the above described functionality without a server? We definitely need a temporary store which doesn’t get destroyed on page refresh. What does not gets destroyed even on refreshing the page and remains on client? Yeah! It’s the client itself. Here, by saying the client we mean the Browser.

Browser window remains even on page refresh and so remains the ‘window’ object. The window object, which is considered as the grand-father of all DOM elements in the beautiful world of JavaScript. So, here we use the window object to attach our key value pairs with it and hence preserving it across the screens since it’s a part of window object now. 

We will point out a bad javascript practice here. Since we are using a property of window object which is currently not used by the page, on actual use of this property our values can be destroyed or over-ridden or they can overload the browser and crash it unexpectedly (too dangerous!). So instead of storing those values in a persistent object, we are piggy-backing the browser memory.


                                win.name = value


But how do we make the data transferrable from one screen to other as raw types? Answer lies in the golden works of Sir Douglas Crockford.
Say it! Its JSON.


                                                   JSON.stringify(win.name) 


We can use our key-value pair to be stored as name attached to window object and on page unload, we can save the values by strigify-ing the json data. After setting this value we can get it anywhere till the session is cleared, hence creating temporary cache storage on client side.

Here is an attached zip file containing a small demo to store values on one page and displaying on other. All JavaScript files are present inside the project. Feel free to use or modify according to your requirement.

 Download the demo project from HERE! 


Inspire:Learn:Contribute

No comments:

Post a Comment