When using libraries like jQuery, it is typical for developers to use selectors to access and manipulate elements in the <abbr=”Document Object Model”>DOM. When a selection is being accessed repeatedly on a webpage, it is a good idea to cache it for better performance.

Let’s consider an example,

jQuery(document).ready(function() {
	jQuery('#some-selector').on('hover', function() {
		jQuery(this).fadeOut('slow').delay(400).fadeIn();
		console.log(jQuery(this).text());
	});

	jQuery('#another-element').on('hover', function() {
		jQuery(this).slideUp();
	});

	jQuery('#some-selector').on('click', function() {
		alert('You have clicked a featured element');
	});	

	jQuery('#another-element').on('mouseout', function() {
		jQuery(this).slideUp();
	});
});

As you may have noticed the IDs ‘some-selector’ and ‘another-element’ are mentioned twice in the above code snippet. By caching these selectors to variables, they can be re-used thereby avoiding any repitition.

As you start to accumulate various selections in your jQuery code, you will appreciate the beauty of maintaining cached selectors in an object – as property, value pairs. This makes it easier for accessing them anywhere in your script and maintenance of these selectors will be a breeze.

With cached selectors in place, the revised code may look like,

var someNamespace_Dom = {
	someSelector : 'jQuery("#some-selector")',
	anotherElement: 'jQuery("#another-element")',
};

jQuery(document).ready(function() {
	someNamespace_Dom.someSelector.on('hover', function() {
		jQuery(this).fadeOut('slow').delay(400).fadeIn();
		console.log(jQuery(this).text());
	});
	someNamespace_Dom.anotherElement.on('hover', function() {
		jQuery(this).slideUp();
	});
	someNamespace_Dom.someSelector.on('click', function() {
		alert('You have clicked a featured element');
	});
	someNamespace_Dom.anotherElement.on('mouseout', function() {
		jQuery(this).slideUp();
	});
});

As the selectors are already cached to variables, the DOM tree doesn’t have to be traversed again to identify the elements being manipulated. The ‘someNamespace_Dom’ object can be used to add further property, value pairs thereby making maintenance a breeze.

If you would like to know more about this topic, I highly recommend checking out the screencast The importance of caching jQuery selections by Adam Sontag.