Cache jQuery Selectors for Better Performance

When selecting elements in jQuery you sometimes want to reuse the selection again later on in your code. A jQuery selection basically is searching your DOM for specific elements based on what you specify inside of $().

For Example:

1
2
$('#YourSelection').text('Change Text!');
$('#YourSelection').css('color','red');

For a light application this is completely acceptable. However, if you are looking to get optimal performance from your application, you will want to cache your selection in a JavaScript variable.

For Example:

1
2
3
var yourSelection = $('#YourSelection');
yourSelection.text('Change Text!');
yourSelection.css('color','red');

In the example above you will see that we are storing our selection in the JavaScript variable ‘yourSelection’. Then when we need to use our jQuery selection again in our code all we have to do is call ‘yourSelection. This is more efficient because every time you call $() you are basically saying “Hey, jQuery. Search the entire DOM for this element.” When you call it again you are doing the same thing even though jQuery has already found the selection you are looking for. So, by storing this jQuery selection in a JavaScript variable you are basically saving on DOM searches and pulling the information from cache; hence, improving performance of your application.

Update:
As Reddit user isometriks pointed out; best practice for the above code would be to chain these two actions together avoiding the necessity of caching the selection. However, anytime you need to call the same selection more than once you should cache the selection.

1
2
var yourSelection = $('#YourSelection');
yourSelection.text('Change Text!').css('color','red');

Comments

comments