A simple way to cache a selector in an object using jQuery
- 2020-06-22 23:46:52
- OfStack
When using libraries like jQuery, developers often use selectors to access and manipulate elements in DOM. When an option is visited repeatedly on a page, it is a good idea to cache it for better performance.
Let's look at 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, ID 'some-ES12en' and 'another-ES14en' are mentioned twice in the code snippet above. By storing these selectors in variables, they can be reused and avoid repetitive selection operations.
As you start to accumulate a variety of selectors in your jQuery code, you can see how good it is to cache selectors in the form of key-value pairs in objects. This makes it easier to access them anywhere in the script, and maintaining these selectors is a breeze.
After caching the selector, the improved code will look something 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 is already cached in the variable, the DOM tree no longer needs to be iterated over to find the element being manipulated. The 'someNamespace_Dom' object can be used to add more key-value pairs, making maintenance easy.