Darcy ClarkeDevelopment / Design / UX

Toggle Main Navigation

Jun 8, 2011

Caching within your Javascript Applications

Posted in "development"

It's important to remember that writing good Javascript includes writing scalable Javascript. Little optimizations can always be implemented and best practices are good to keep in mind. Training yourself to write code like this can be a bit tasking but I promise, you'll really enjoy doing things like caching and optimizing selectors once you've begun.

I wrote a post awhile back called "Javascript Applications 101". It's a great starter / boilerplate for getting your projects off on the write path. That said, I left a lot of things out that really help make things fast. Caching, for one, is extremely important. In most of my applications I use a single object to hold cached data/selectors and then specify other areas to be cached within their own dedicated namespaces (like: App.mail etc.). Let's take a look at that code.

var App = {};
App.cache = {};

I've left out all the other methods / objects I usually add to my "App" namespace for now. If you want to read more about that jump over to the Javascript Applications 101 post I linked to above.

As you can see, I've added the App.cache which is a general object I use to store all my selectors. Using something like App.cache ensures that you aren't making unnecessary DOM traversals for information you've already asked for. That said, it's important to note that the selectors are mere references to the DOM objects so that changes that occur within these objects will indeed be reflected when you go to manipulate the cached selector down the line. We can test this by doing the following:

<iframe style="width: 100%; height: 300px; border: 1px solid #ccc;" src="http://jsfiddle.net/darcyclarke/gt8xS/embedded/js,html,css,result"></iframe>

In this jsFiddle I cache a selector, manipulate it, and then use my cached selector to log the contents. Happy coding!