This article briefly discusses the issue of optimizing jQuery code from the perspective of selectors.
The operating mechanism of Sizzle
Starting from 1.3, jQuery has separated the code for finding elements based on selector expressions, which is the Sizzle engine. When we pass a selector expression (such as "#id", ".class", ":nth-child(2)") to the $() function, Sizzle will internally preferentially use the DOM natively supported by the browser. Method to find elements for maximum execution speed. The following are several standard native methods that Sizzle will preferentially use (the purpose of each method will not be described in detail):
If the browser does not support a method, Or the incoming selector expression is not a standard selector (such as ":eq()", ":odd" or other custom selectors), Sizzle will use document.getElementsByTagName('*') to get the elements in the document all elements before looping through and testing each one. Obviously, this is a method that should only be used as a last resort; it is conceivable that this most stupid method is also the least efficient.
Optimization Example For example, suppose we want to get all the text boxes in the page form, that is:
The first selector is a standard CSS attribute selector, and the second selector is a custom selector . According to the previous analysis of the Sizzle engine, in most modern browsers (browsers that support the native querySelectorAll() method), the first selector is much faster than the second.
Give another example. Suppose there are the following two jQuery queries:
The first query first finds all input elements through standard CSS element selectors, and then calls jQuery's eq() method obtains the second element in the matching result (the index parameter of the eq() method is calculated from 0). The second query uses a custom pseudo-class selector: eq(). It can be seen from the test that the first method is much faster than the second method.
Conclusion Use the selectors specified in the CSS specification as much as possible. Unless there is no standard selector, consider using jQuery's custom selector.
(Note: This article is based on the relevant chapters of "JQuery Basics Tutorial (3rd Edition)".)
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