Working Principle and optimization of jQuery Selector

Source: Internet
Author: User

 

As for those selectors, they are available in the help manual. This article mainly analyzes their working principles and optimizes the selectors we write, especially when there are many pages, optimization is needed. Let's get down to the truth.

 

Every time you declare a jQuery object, jQuery is returned. prototype. the init object is obviously jQuery. fn method. Actually, this is not a method, but an init constructor. Because JavaScript prototype objects can be inherited by implementation, adding JavaScript objects to references is not a copy, new jQuery, new jQuery. fn and new jQuery. fn. the sub-objects of init are the same, but there are no differences in the execution of init. Here we will not talk about the reason. Wait for the next article to explain why it is like this.

 

When we use the selector $ (selector, content), The init (selectot, content) will be executed. Let's see how the execution in inti is:

 

If (typeof selector = "string "){

 

// Regular Expression matching. Check whether the code is HTML or # id.

 

Var match = quickExpr.exe c (selector );

 

// No DOM Element Set, document, or jQuery object to be searched.

 

// Selector is # id format

 

If (match & (match [1] |! Context )){

 

// HANDLE: $ (html)-> $ (array)

 

// HTML code, call clean to complete HTML code

 

If (match [1]) {

 

Selector = jQuery. clean ([match [1], context );

 

}

 

// Yes: $ ("# id ")

 

Else {

 

// Determine whether the id Dom is loaded

 

Var elem = document. getElementById (match [3]);

 

If (elem ){

 

If (elem. id! = Match [3])

 

Return jQuery (). find (selector );

 

Return jQuery (elem); // return after execution

 

}

 

Selector = [];

 

}

 

// Non-id format. Search in context or full text

 

} Else {

 

Return jQuery (context). find (selector );

 

}

 

}

 

Here, we can see that only the selector writes $ ('# id') as quickly as possible. It is equivalent to executing getElementById once, and subsequent programs do not need to be executed. Of course, the selector we usually need is not that simple. For example, we need to set the CSS under the id to className and write $ ('# id. classname') and $ ('# id '). find ('. classname'); the execution results of the two statements are the same, for example, <div id = "id"> <span class = "className"> </span> </div>, the returned results must all be <span class = "className"> </span>, but the execution efficiency is completely different.

 

After analyzing the code above, if it is not a simple selector like $ ('# id'), we will execute the find function. Then let's take a look at how find works:

 

Find: function (selector ){

 

// Search for the current object

 

Var elems = jQuery. map (this, function (elem ){

 

Return jQuery. find (selector, elem );

 

});

 

// The code below can be ignored, just for some processing

 

// The static method test of the js regular object is applied here.

 

// IndexOf ("...") You need to understand the xpath syntax, that is, to determine the method of determining that the selector contains the parent node.

 

// The intention is to filter the repeated elements of the array

 

Return this. pushStack (/[^ +>] [^ +>]/. test (selector) | selector. indexOf ("..")>-1?

 

JQuery. unique (elems ):

 

Elems );

 

}

 

If you write $ ('# id. classname'), and the extended find ('# id. classname', document), because the current this is the jQuery array of the document, we are looking at the implementation of the extended find. If there are many codes, it will not be listed, in short, we start to find the first sub-node of the dom that is passed by the second parameter. for more information, see <+. If we want to optimize it, is it necessary to try to minimize the range of the second context parameter, so that traversal is very rare?

 

If we write $ ('# id') like this '). find ('. classname'), the program is only executed in this way. When init is used for the first time, execute getElementById and return, and then execute find ('. classname', divDocument), divDocument is the div tag we selected for the first time. If there are many dom objects in the document, this time we only traverse divDocument many times, in addition, the id Selection Speed for the first time is much faster than the traversal speed.

 

Now you should understand it. That is to say, the first layer is the best choice of ID, but a simple selector, with the goal of defining the range and improving the speed. This time we will talk about the optimization of the choice of writing and other optimizations, and we will talk about it next time.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.