Home > Web Front-end > JS Tutorial > Simple way to cache selectors in objects using jQuery_jquery

Simple way to cache selectors in objects using jQuery_jquery

WBOY
Release: 2016-05-16 15:52:17
Original
1143 people have browsed it

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();
  });
});
Copy after login

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();
  });
});
Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template