Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.

Channels ▼

Web Development

Using the jQuery Cache

In client Web applications, data storage is an area of growing importance. Local storage concerns data being saved permanently on the client, and is similar to cookies but much more flexible and richer in functionality. It is a safe bet that local storage will replace certain uses of cookies in the long run — for example, to store user-specific data. Local storage is about caching data on the client in a persistent state (an in-memory cache is a different kind of thing, but it still has its own space). Some browsers currently support forms of local storage even though the API is not yet unified.

Without a unified API for client-side caching, each application has to create its own set of global variables and group them in a reasonable data structure that is application specific. Wouldn't it be nice if we could rely on a well-done and common API for caching, general enough to look like a dictionary? The jQuery library offers just this — a simple but quite effective API to store data in the browser's memory for the duration of a session (any data you park in the jQuery cache is lost once you close the browser window).

The data Function

The jQuery cache is centered on the data function. Like any other jQuery function, data also applies to the wrapped set resulting from a query. The data method, in particular, allows you to associate some arbitrary data with all elements that match the selector. It should be noted that most of the time, you'll use selectors that just match a single DOM element. However, if multiple elements are selected, no data duplication will ever occur — just the reference is duplicated, not the data.

The jQuery cache is implemented as a plain dictionary where each element is characterized by a name and a value. To accommodate naming conventions that ensure the uniqueness of entries, binding data to DOM elements is a helpful way to simplify naming (in full respect of the jQuery philosophy). Cached entries can have the same name as long as they are bound to different DOM elements.

Working with Data in the In-Memory Cache

To add data to the cache, you select the DOM element and then invoke the data function passing key and value.

$("#TextBox1").data("Hint", value)

The cache is useful for storing data you download once and reuse frequently within the page. When you have a master/detail view and you get data for the detail view via Ajax, a call to the data function may save you roundtrips within the same session. Imagine you have a user interface where you allow users to select records matching a given selection; say, all customers with names beginning with "A."

The first time a user selects A, you download all matching records. Next, you cache these records to memory. The next time the user selects the same letter, instead of placing a second request, data is simply retrieved from the cache.

A couple of design patterns are related to this approach. The first is Predictive Fetch, which means that an application should try to guess future requests it may receive from an application. If the guess is right, data is downloaded asynchronously and presented to the user on demand with no delay or latency. If the guess is wrong, you simply made some extra download effort for nothing. Another related pattern is Cache Aside, which is a pattern used in the implementation of a caching layer. According to the pattern, you split your data layer in two parts — the classic data source and an additional caching layer on top of it. This design works well both on the server and the client side. On the client side, it can be implemented using jQuery to place Ajax calls to remote URLs and using the data function to cache responses on the client to save roundtrips.

Once placed in the cache, the data never expires and must be removed manually to free up memory. To remove a piece of data from the cache, you use the removeData method.



Building an application-specific caching layer in JavaScript is not difficult and is precisely what most developers do when they organize their global variables. Having a tested and fully working dictionary-based API, however, makes everything faster and easier to achieve. The jQuery library has this ace up its sleeve.

Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.