18 surprises for reading jQuery source code

Source: Internet
Author: User

18 surprises for reading jQuery source code

I love jQuery, and although I think I am a senior JavaScript developer, I have never tried to read jQuery source code from the beginning to the end until now. Here are some things I learned along the way:

Note: I use$.fn.method()Syntax to call a group of matching elements. For example$.fn.addClass, Indicates$('div').addClass('blue')Or$('a.active').addClass('in-use')Usage of this class.$.fnIs the prototype of jQuery packaging elements.

1. Sizzle weight:Sizzle is the selector engine used by jQuery to find elements in DOM, based on CSS selector. It exactly sets$('div.active')Convert to an array of operational elements. I know that Sizzle accounts for a large part of jQuery, but its size still scares me. It is undoubtedly the only and largest feature in jQuery. I estimate that it accounts for 22% of the total code base, and the second largest feature --$.ajaxOnly accounts for 8%.

2. $. grep:This method works with Underscore's_.filterSimilar. Two parameters, one element array and one function, are used to execute functions for each element in sequence, and an element array whose execution result is true is returned.

3. Bubble prohibited:JQuery plaintext prohibitedloadEvent bubbles. Internally, jQueryloadThe specialnoBubble: trueMark, soimage.loadEvents do not bubblewindowTrigger by mistakewindow.loadEvent.

4. Default animation speed:JQuery implements element animation effects by rapidly changing style attributes consecutively. Each small change is calledtick. The default animation speed is every 13 milliseconds.tickTo change the speed, you can rewrite it.jQuery.fx.intervalTo the integer you want.

5. fn. addClass can accept functions:We usually$.fn.addClassProvides a string containing the class name to create elements. But it can also accept a function. This function must return a string separated by spaces. Here is another egg. This function accepts indexes of matched elements as parameters. You can use this feature to construct intelligently changed class names.

6.Fn. removeClass is also the same:Like above, it can also accept a function. This function also automatically receives the index of the element.
7.: Empty pseudo selector:It can be easily used to match elements without children.

8.: Lt and: gt pseudo selector:They match the elements based on the index of the elements in the matching set. For example$('div:gt(2)')Alldiv, Except for the first three from 0 ). If you input a negative number, it starts from the end.

9.$ (Document). ready () commitment:JQuery seems to have used its own stuff. Reliable internal$(document).ready()A jQuery latency is used to determine when the DOM is fully loaded.

10. $. type:You must be familiartypeofTo determine the data type, but do you know that jQuery provides.type()Method? JQuery is more intelligent than native. For exampletypeof (new Number(3))Returnobject, And$.type(new Number(3))Returnsnumber. Update: As ShirtlessKirk pointed out in the comment,$.typeReturns.valueOf()Attribute. So the more accurate statement is:$.typeIndicates the type of the returned value of an object.

11. $. fn. queue:You can use$(‘div’).queue()You can view the effect queue of an element to easily understand the effect of the element. More effectively, you can directly operate the queue to add results. Extracted from the jQuery document:

 
 
  1. $( document.body ).click(function() {  
  2. $( "div" )  
  3.     .show( "slow" )  
  4.     .animate({ left: "+=200" }, 2000 )  
  5.     .queue(function() {  
  6.         $( this ).addClass( "newcolor" ).dequeue();  
  7.     })  
  8.     .animate({ left: "-=200" }, 500 )  
  9.     .queue(function() {  
  10.         $( this ).removeClass( "newcolor" ).dequeue();  
  11.     })  
  12.     .slideUp();  
  13. }); 

12. disabling an element will not trigger the click event:JQuery is not executed for disabled elements by default.clickWith this optimization, you do not need to use the code to check it again.

13. $. fn. on acceptable objects:You know$.fn.onCan I accept an object to connect multiple events at a time? Example of the jQuery document:

 
 
  1. $( "div.test" ).on({  
  2. click: function() {  
  3.     $( this ).toggleClass( "active" );  
  4. }, mouseenter: function() {  
  5.     $( this ).addClass( "inside" );  
  6. }, mouseleave: function() {  
  7.     $( this ).removeClass( "inside" );  
  8. }  
  9. }); 

14. $. camelCase:This useful method can convert a character string into a camper string.

15. $. active:Call$.activeReturns the number of XHR (XML Http Request) queries. You can use it to manually limit the concurrency of AJAX requests.

16. $. fn. parentsUntil/$. fn. nextUntil/$. fn. prevUntil:I'm familiar.parents(),.next()And.prev()But I don't know if there are other methods. They will match all parent/next/previous element until) and encounter elements that meet the termination condition.

17. $. fn. clone parameters:When you use.clone()Clone an element. You can usetrueAs the first parameter to clone the data attribute data attributes of the element) and events.

18. More $. fn. clone parameters:In addition to the above method, you can upload another one.trueParameter to clone the data attributes and events of all children of the element. This is called "Deep clone ". The default value of the second parameter is the same as that of the first parameter. The first parameter defaults to false ). So when the first parameter istrueAnd you want the second parameter to betrueYou can ignore the second parameter.

This article is translated from quickleft by bole online-Jaward Hua Zi

Related Article

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.