jQuery - caching selectors
In jQuery, “caching selectors” is a performance optimization technique where you store the result of a jQuery selector in a variable instead of querying the DOM multiple times. This is important because every time you write a jQuery selector like $('#myDiv'), jQuery searches the DOM to find that element, which can be costly if done repeatedly in loops or event handlers.
Here’s a detailed breakdown:
1. What it means
Instead of doing this:
$('#myDiv').hide();
$('#myDiv').css('color', 'red');
$('#myDiv').text('Hello!');
jQuery searches the DOM three times for #myDiv.
By caching the selector, you search the DOM once:
var $myDiv = $('#myDiv'); // cache the selector
$myDiv.hide();
$myDiv.css('color', 'red');
$myDiv.text('Hello!');
Here, $myDiv stores the jQuery object, and all subsequent operations use this cached reference.
2. Why it matters
-
Performance improvement: Fewer DOM queries means faster code, especially in loops or heavy pages.
-
Cleaner code: Makes it obvious that the same element is being reused.
-
Reduces bugs: If the selector is complex, caching ensures consistency.
3. Best practices
-
Prefix cached variables with
$to indicate they hold a jQuery object:
var $listItems = $('.list-item');
-
Cache elements used repeatedly inside loops or event handlers:
$('.list-item').each(function() {
var $this = $(this); // cache 'this' element
$this.addClass('highlight');
});
-
For elements that don’t change frequently, caching is very effective. For dynamic content added later, you may need to query again or use event delegation.
4. Example
Without caching:
for (var i = 0; i < 100; i++) {
$('#content').append('<p>Line ' + i + '</p>');
}
Here, #content is searched 100 times.
With caching:
var $content = $('#content');
for (var i = 0; i < 100; i++) {
$content.append('<p>Line ' + i + '</p>');
}
Now, #content is searched once, which is much faster.