When using a library like jQuery, developers often use selectors to access and manipulate elements in the DOM. When a selection is accessed repeatedly on the page, it's a good idea to cache it for better performance.
Let’s see 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(); }); });
Perhaps you have noticed that the IDs ‘some-selector’ and ‘another-element’ are mentioned twice in the above snippet. By saving these selectors into variables, you can make them reusable and avoid repeated selection operations.
When you start accumulating various selectors in your jQuery code, you can appreciate how nice it is to cache selectors in objects - as key-value pairs. This makes it easier for you to access them from anywhere in your script, and maintaining these selectors is a breeze.
After caching the selector, the improved code will look like this,
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(); }); });
Since the selector has been cached in the variable, the DOM tree no longer needs to be traversed repeatedly to find the element to be operated on. The 'someNamespace_Dom' object can be used to add more key-value pairs, making maintenance easy.