When using libraries such as jquery, developers often use selectors to access and manipulate elements in the DOM. When a choice is repeatedly accessed on the page, it's a good idea to cache it for better performance.
Let's take a look at an example,
jquery (document). Ready (function () {
jquery (' #some-selector '). On (' hover ', function () {
jquery (this). Fadeout (' slow '). Delay. 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 ();
});
You may have noticed that the ID ' some-selector ' and ' another-element ' were mentioned two times in the code snippet above. By saving these selectors to variables, you can make them reusable and avoid repetitive selection operations.
When you start to accumulate a variety of selectors in your jquery code, you can see how wonderful it is to cache selectors in objects--in the form of key-value pairs. This makes it easier for you to access them anywhere in the script, and it's easy to maintain those selectors.
After caching the selector, the improved code is 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. 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 ();
});
Because the selector is already cached in a 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 work easy.