Jquery source code analysis (modification)

Source: Internet
Author: User
Tags mootools
  1. 1, Overview
  2. Jquery is a very good JS library. Compared with many JS class libraries such as prototype, Yui, and mootools, it is a powerful tool, starting from the practical point of view of web development, aside from some other useless items in Lib, it provides developers with a short and concise class library. It is short, concise, easy to use, efficient in performance, and can greatly improve the development efficiency. It is one of the best auxiliary tools for developing web applications. Therefore, most developers discard prototype and choose jquery for web development.
  3. When using jquery, some developers often encounter many problems because they only know how to use jquery and do not understand the running principle of jquery. Most of these problems are caused by improper use, and few of them are jquery bugs. If you do not understand the running mechanism and core source code, it is difficult to write a high-performanceProgram.
  4. When debugging A jquery-based program, we need to track the status of the jquery object for analysis most of the time,CodeUnlike ext and Yui, its code is a bit obscure and hard to understand. That is to say, if you want to use jquery well, you must be clear about its source code.
  5. Jquery has rich network resources, but Baidu has been around for a long time, but it is difficult to find a document that fully analyzes jquery source code. It is jquery's developer. John Resi's "Pro JavaScript techniques" involves the analysis of jquery's source code. It can be seen as jquery's source code analysis, but it mainly refers to the use of JavaScript. We do not understand it very well. We carefully understand the jquery source code.
  6. 2, Jquery object
  7. In this section, we will analyze and describe the jquery operating mechanism and design concept. This section consists of jquery's system, construction, and array features.
  8. 2.1Jquery Design Philosophy
  9. Before using jquery, we all ask what jquery is? Jquery is a class library that provides auxiliary functions for Web JS development like prototype and mootools. So why jquery? Before jquery appeared, prototype and Yui were all mature JS frameworks with different characteristics. Why abandon them and use jquery, which is an outstanding feature, to attract developers?
  10. To answer this question, we must understand jquery's design philosophy. Recall or imagine how we use Js in Web development? Most of the time, getelementbyid is used to find the DOM element in the DOM document, and then the value or set value, innerhtml is used to retrieve or set its content, or event listening (such as click ), in terms of style control, we will change the height, width, and display to achieve visual effect. For Ajax, it is also used to add content to an element of the page.
  11. To sum up, we are operating the DOM elements. This element may be one or more. This element may be a document, window, or DOM element. In this way, our task is the second largest part. One is to find the DOM element, and the other is to operate the DOM element.
  12. Be familiar with it, whether using direct search like getelementbyid or using element. the indirect search methods such as lastchild are not very difficult. For Dom elements, Dom operations are also very rich and not very difficult to use? So what is the use of the Class Library? The most difficult problem is browser compatibility. All JS frameworks must solve this problem and simplify the built-in operations of Js.
  13. Prototype can be said to have created a precedent for JS class libraries, giving us a fresh feeling. It solves the compatibility issues of most browsers. At the same time, it simplifies the issue of errors written by regular books with long and difficult to remember original function names (replacing getelementbyid with $ (XX), provides Ajax access, extends array, object, functions, events, and other JS native objects.
  14. But these still cannot meet the development needs. For example, to search for DOM elements in the DOM tree, we can only use the element ID, but we want a more convenient search method, at the same time, we also hope to have a unified entrance. The learning curve is too high or difficult to use.
  15. Jquery is here to unify everything in the jquery object. Jquery objects are used. In fact, jquery's pioneering work is like its name: query. Its powerful search function eclipses all frameworks.
  16. Jquery is actually a queryer. On the basis of the queryer, you can also perform operations on the searched elements. In this way, jquery is the unified query and operation. Queries are portals and operations are results.
  17. Jquery can also be divided into two parts in implementation. One part is jquery's static method, which can also be called a practical method or a tool method. It is directly referenced through the jquery namespace of jquery. XXX. The second part is the jquery instance method. The jquery instance is generated through jquery (XX) or $ (XX) and then referenced through this instance. Most of these methods are implemented by using static method proxies. Real functional operations are implemented in jquery's static method.
  18. These functions are subdivided into the following parts:
  19. 1, Selector, search for elements. This search not only contains ~ CSS selector of css3 also includes some functions that can be extended for direct or indirect searches.
  20. 2And Dom element attribute operations. DOM elements can be viewed as HTML tags. Operations on attributes are operations on the attributes of tags. This attribute operation includes addition, modification, deletion, and value.
  21. 3And DOM elements. CSS controls the display of pages. Operations on CSS must include common CSS functions such as height, width, and display.
  22. 4And Ajax operations. Ajax is used to asynchronously fetch data from the server and perform related operations.
  23. 5And event operations. Unified processing of event compatibility.
  24. 6, Animation (FX) operations. It can be seen as an extension of CSS styles.
  25. 2.2, Jquery Object Construction
  26. Generating or constructing a jquery object is actually building and running a selector ). Since it is a query, the results (DOM element) will certainly be searched before these results will be operated. So where are the search results stored? The best part is, of course, the inside of the jquery object. The search result may be an element or multiple elements, for example, a nodeset set ). That is to say, there is a set inside the jquery object. This collection stores the DOM elements found.
  27. But the jquery object mentioned in the previous section is the unified entry for all operations, so its construction cannot be limited to finding Dom elements from the DOM document, it may also be a DOM element transferred from another collection, or a DOM element generated from an HTML string.
  28. The jquery document provides four methods: jquery (expression, [Context]), jquery (HTML), jquery (elements), and jquery (callback) there are four ways to create jquery objects. Jquery can be replaced by $. These four types are frequently used. In fact, jquery parameters can be any element and can constitute jquery objects.
  29. For example:
  30. 1, $ ("P"), we can see that the parameter can be a set of jquery objects or arraylike.
  31. 2And $ () is short for $ (document.
  32. 3, $ (3)3Put it in a collection of jquery objects.
  33. For $ (3The element (such as the element in the arraylike set) is not a DOM element. It is best not to construct a jquery object. The jquery object method is for DOM objects. If you do not know how to use it, it is likely to cause errors.
  34. As mentioned above, it is still difficult to understand its principles. Now we will analyze it from the source code perspective:
  35. No object is generated by calling jquery (XXX). ItsThisIs directed to the window object. So how do jquery's instance methods inherit from them? Take a look:
  36. VaR jquery = Window. jquery = Window. $ = function (selector, context ){Return NewJquery. FN. INIT (selector, context); ①
  37. };
  38. This is the general entry of jquery. The jquery object does not actually pass throughNewJquery () inherits the methods in its prototype. The jquery object is actually the object generated by the jquery. FN. init function. We can see that it is of little significance to add some function set objects for jquery. prototype. Because weNewJquery () is acceptable, but the generated jquery object isReturnWill be discarded. So it is best not to useNewJquery () to build jquery objects.
  39. The jquery object is actuallyNewJquery. FN. init. Therefore, jquery. FN. init. prototype is the operation method for hanging jquery objects. For example
  40. Jquery. FN. init. Prototype = jquery. FN;
  41. You may worry about589Then, put the functions in jquery. FN into jquery. FN. init. Prototype. What should we do through jquery. FN. Extend later? Here is actually a reference to jquery. fn. When extending jquery, you only need to extend the relevant function extend to jquery. fn.
  42. Now let's take a look at how jquery. FN. init completes the work:
  43. Init: function (selector, context ){
  44. Selector = selector | document;// Confirm that the selector exists
  45. // In the first case, handle $ (domelement) indicates a single Dom element, ignoring the context
  46. If(Selector. nodetype) {②
  47. This[0] = Selector;
  48. This. Length =1;
  49. Return This;
  50. }
  51. If(Typeof selector ="String"){// Selector is string ③
  52. VaR match = quickexpr.exe C (selector );
  53. If(Match & (Match [1] |! Context )){
  54. If(Match [1])// Process the second scenario $ (HTML)-> $ (array) ④
  55. Selector = jquery. Clean ([Match [1], Context );
  56. Else{// Case 3: handle: $ ("# ID") // process $ ("# ID ")
  57. VaR ELEM = Document. getelementbyid (Match [3]);
  58. If(ELEM ){
  59. // Ie returns the name = ID element. If so, document. Find (s)
  60. If(ELEM. ID! = Match [3]) ⑤
  61. ReturnJquery (). Find (selector );
  62. // Construct a new jquery (ELEM)
  63. ReturnJquery (ELEM); ⑥
  64. }
  65. Selector = [];
  66. }
  67. }Else
  68. // Case 4: Processing $ (expr, [Context]) =$ (content). Find (expr)
  69. ReturnJquery (context). Find (selector); 7
  70. }Else If(Jquery. isfunction (selector) returns// Case 5: Process $ (function) 7shortcut for document ready
  71. ReturnJquery (document) [jquery. FN. Ready?"Ready":"Load"] (Selector );
  72. // Case 6: Process $ (elements)
  73. Return This. Setarray (jquery. makearray (selector); optional
  74. },
  75. Jquery. FN. init analyzes the passed parameters and generates jquery objects. Its first parameter is generally required (if it is null, It is the default document ). From the source code perspective, the first parameter has the following four types:
  76. Type description
  77. Dom Element
  78. The first parameter is the DOM element, and the second parameter is not required. Directly store the DOM element in the collection of newly generated jquery objects. Returns the jquery object. The jquery object is built.
  79. String
  80. The first parameter is string in three cases:
  81.  1, HTML Tag string, $ (HTML)-> $ (array), the second parameter is optional.
  82. Run selector = jquery. Clean ([Match [1], Context );. This statement converts a hteml string to an array of DOM objects. Then, return the array type.
  83. 2When the string is # ID $ (ID)
  84. First, use VaR ELEM = Document. getelementbyid (Match [3]); Obtain ELEM. If selector = [] is not obtained, convert it to the jquery object that returns an empty set of values of the array type.
  85. For example, if ELEM is foundReturnJquery (ELEM); The jquery object is generated again. This is the return of the jquery object of the DOM element type.
  86. 3Compatible with css1-3The selector string of the syntax. The second parameter is optional. RunReturnJquery (context). Find (selector );. This statement runs jquery (context) first ). We can see that the second parameter of context can be any value or a set form. Then, we can use find (selector) to find a set of DOM elements in jquery (context) that satisfy the selector expression, construct a new jquery object, and return the result.
  87. # ID is actually consistent with this method. It is used separately to improve performance.
  88. FN
  89. The first parameter is the function. The second parameter is not required. Is short for $ (document). Ready (FN ).ReturnJquery (document) [jquery. FN. Ready?"Ready":"Load"] (Selector) is the code it executes. This statement first executes jquery (document). It returns the newjquery. FN. init function to generate a jquery object (the element is document ). Call the ready (FN) method of this object. Ready (FN) returns the current object. The preceding statement returns the returned object of this ready (FN.
  90. As you can see, $ (FN) returns the $ (document) object. The $ (FN) object generated for the first time is discarded.
  91. Array
  92. The first parameter is all types except the DOM elements, functions, and strings mentioned above. It can be null, for example, $ (). The second parameter is not required.
  93. Statement:Return This. Setarray (jquery. makearray (selector ));
  94. It first converts the first parameter to an array. Selector can be an array-like set, such as a jquery object, such as a DOM Element Set returned by getelementsbytag. It may support $ (This). Selector may also be a single arbitrary object.
  95. After being converted to a standard array, runThis. Setarray saves all the elements in this array to the current collection of jquery objects. Then, the current jquery object is returned.
  96. In fact, DOM elements may be integrated here, which can be taken separately to improve performance.
  97. From the code above and the above table, we can also see that building a jquery object is to add elements to the collection of jquery objects (usually DOM elements ). The added element has two forms:
  98. One is a single element. It may be in the form of passing parameters of the DOM element directly. You can also use # ID to find the element from the DOM document.
  99. Second, collections, such as jquery objects, arrays, Dom sets found through CSS selector, and other array-like.
  100. The above table only analyzes the type of the input parameter. How can this problem be solved? In step 5, it implements css1 ~ Css3 is compatible with selector lookup functions. Use jquery (). Find (selector); to analyze the string and find the element set in the DOM document tree that complies with the passed selector syntax.
  101. At ④, it converts HTML strings into a collection of Dom element nodes. This is done through jquery. Clean ([Match [1], Context.
  102. At the handler, it implements the unified entry of domready's jquery object. We can use $ (FN) to register domready's listening function. All functional code that calls jquery should be run after domready. $ (FN) is the entry to all functional code in application development. It supports any number of $ (FN) registrations. It is throughReturnJquery (document) [jquery. FN. Ready?"Ready":"Load"] (Selector.
  103. After the elements are found, the set is constructed.This. Setarray (jquery. makearray (selector); to build a set inside the jquery object. The following section analyzes how the set is implemented.

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.