I recently wanted to take a look at the jQuery source code, and found this blog "10 Things Learned from the jQuery Source Code"
This article is based on this video blog, and has refined some content to share with you.
Note:
This article was written in 2010. The author used jQuery 1.4 version in the video. Based on the content mentioned in the video, I correspond to the current 1.11 version Some adjustments have been made, some abandoned or removed content pages have been deleted, and I would like to thank the original author
黑Box/Black box
黑BoxSystem The concept is a system that returns output given input, and the black box encapsulates the implementation process. The jQuery black box mentioned here is to output jQuery and $ for the js global variable window, and the process is encapsulated in the black box and does not interfere with the outside world.
The black box of jQuery 1.4 version uses a self-executing function similar to the following
(function( window, undefined){})(window)
The author gave a more general method to implement the black box
undefined = true; (function(window, document, undefined){ if(foo == undefined) { } })(this, document)
jQuery There is a third additional formal parameter called undefined in the black box, but no value is passed when passing the actual parameter. Formal parameters without a value in js will be set to undefined, which ensures the correctness of undefined inside the black box. In js, undefined, as a global property, can be assigned a value. For example, undefined = true in the above code;
Another benefit of implementing the black box in the self-executing function mode is that it is beneficial to For compression, as in the case below, we only need to use simple variables inside the black box.
(function(A, B, C)){ B.getElementById('') })(this, document)
The author gives many examples of self-execution for Anonymous function, such as the following one, which continuously updates (and continuously executes) a certain part of the page
(function loop(){ doStuff(); $('#update').load('awesomething.php',function(){ loop(); }) //setTimeout(loop, 100) })()
The black box of jQuery version 1.11 adopts a new factory method. This article does not explore the implementation of
noConflict
The difference of this function is not big. The code of version 1.11 is as follows
var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; };
We can I saw that the implementation of anti-conflict is to save the previous JQuery and $ first, and then return them when noConflict is called.
Conversion with native js attribute naming
For version 1.4 It is the props object to store the correspondence between jquery's property operationsand native js property operations
The reduced version of version 1.11 is like this
jQuery.extend({ propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { //... name = jQuery.propFix[ name ] || name; }, propHooks: { //... } }); jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; });
propFix This object stores the correspondence table. For example, class is converted into className, and the prop function is responsible for processing this relationship table.
The following each is very interesting. Traverse the properties in the array, then map their lowercase format to itself, and put it in propFix
Special effect Speed
We know For some animations in jQuery, we can directly define the implementation speed through normal, fast, and slow. This is defined in the source code like this
jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 };
The naughty original author did something like this:
var isIE //... jQuery.fx.speeds._default = isIE ? 800 : 400 jQuery.fx.speeds.veryfast = 200; $('...').fadeIn('veryfast')
One is to make conditional judgment on the default attribute, and there is also a custom speed, such as "veryfast"
.ready
ready function version 1.11 and version 1.4 There is a big gap, and I don’t understand many things in the new version. Let’s simply take out the core and take a look at it
jQuery.ready.promise = function( obj ) { //...省略若干 } else if ( document.addEventListener ) { // 使用addEventListener "DOMContentLoaded" 监听ready事件 document.addEventListener( "DOMContentLoaded", completed, false ); // 备选方案 "load" window.addEventListener( "load", completed, false ); //如果IE } else { // Ensure firing before onload, maybe late but safe also for iframes //IE下 attachEvent 的"onreadystatechange" document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work //备选方案onload window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj );}; .ready 利用了下面的.promise去做确保载入完成的工作,重点是document.addEventListener( "DOMContentLoaded", completed, false );window.addEventListener( "load", completed, false );document.attachEvent( "onreadystatechange", completed );window.attachEvent( "onload", completed );
Four checking methods for compatibility considerations
Starting from top, one thing is to do under IE, the dom node determines whether there is scroll. Under IE, if the dom has scroll, the elements that are not scrolled will have an impact on ready. I don’t understand this enough. In short, jQuery A technique called Diego Perini is used. You can see more at the address in the comments.
Selector
$('#id').find('tag.thing') --- faster
$('#id tag.thing') ------- using sizzle
The original author talked about a jquery efficiency issue here. The above method is faster, while the following method is slightly slower. Simply put, it is because of the following The method calls sizzle, which is actually converted into the above mode through sizzle, and the call of id is directly through jQuery.init.
It needs to be expanded here. Let’s take a look at what the jQuery object looks like in 1.11
jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }
The jQuery object actually returns its own constructor is called init, let’s take a look at what init does
// Initialize a jQuery object init = jQuery.fn.init = function( selector, context ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) //超级省略...下略 // Handle HTML strings // HANDLE: $(html) -> $(array) // HANDLE: $(html, props) // HANDLE: $(#id) // HANDLE: $(expr, $(...)) // HANDLE: $(expr, context) // HANDLE: $(DOMElement) // HANDLE: $(function) return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn;
Extracted from the above In the code comments, we can see what situations are handled in jq's own constructor, including the acquisition of html tag names and ids, which means that these two acquisitions are the lowest level. In addition, other processing of $() must go through other function is not as efficient as the above processing situation.
At the same time, we can also see that the prototype of init is assigned to jQuery.fn. Interested friends can learn more about the jQuery object.
jQ’s status selectors, such as:not,:has,:eq are stored in
Sizzle.selectors.pseudos
The above is the detailed content of What should you know about jQuery?. For more information, please follow other related articles on the PHP Chinese website!