JQuery: Special syntax for $ (document). ready ()

Source: Internet
Author: User

When reading a book, I noticed that the following two statements have the same efficacy. $ (function () {alert ("hello! ") ;}); $ (Document). ready (function () {alert (" hello! ") ;}); This special syntax is to replace $ () with $ (document ). ready (), similar to (different) window. onload pop-up window: view the source code of jQuery1.8.3, which is encapsulated as follows: (function (window, undefined ){/*... jQuery source code is all here... */}) (window); the following statement first assigns jQuery encapsulated in the internal window. $, and then assign it to window. jQuery. This means that window. $ and window. jQuery are the same thing in actual use. Because the $ symbol has only one letter, it is shorter than jQuery, so it is more common, but note that $ is not unique to jQuery. Saving the letter price increases the risk of Name Conflict. // Expose jQuery to the global object window. jQuery = window. $ = jQuery; The following is the jQuery initialization Statement (note that the function is not executed at this time): // Define a local copy of jQuery = function (selector, context) {// The jQuery object is actually just the init constructor 'enabled' return new jQuery. fn. init (selector, context, rootjQuery);} Find jQuery. fn definition. This is an object, with a function element called init: jQuery. fn = jQuery. prototype = {constructor: jQuery, Init: function (selector, context, rootjQuery) {var match, elem, ret, doc; // Handle $ (""), $ (null), $ (undefined ), $ (false) if (! Selector) {return this;} // Handle $ (DOMElement) if (selector. nodeType) {this. context = this [0] = selector; this. length = 1; return this ;}/*... the following content is omitted... */continue, there is a logic in init: // HANDLE: $ (function) // your cut for document ready} else if (jQuery. isFunction (selector) {return rootjQuery. ready (selector);} lost, and the definition of rootjQuery returned to jQuery: // All jQuery objects shocould point back to these rootjQu Ery = jQuery (document); recursion means recursion. JQuery is not only a function, but also a recursive function. If you enter a function when calling jQuery, for example, $ (function () {alert ("hello! ");}); Then this function will go to rootjQuery, return to jQuery, and execute jQuery (document). ready. $ Is the same as jQuery. This explains that $ (inputFunction) can replace $ (document). ready (inputFunction ). I don't want to end this article yet. My question is, what does $ (document) do? Well, you still need to go to jQuery. fn. init and check whether the nodeType attribute exists to achieve the "Handle $ (DOMElement)" goal. How to Handle? Specifically, the input parameter (document at this time) is assigned to the context attribute of this and then returns this. That is to say, $ (document) returns jQuery after execution, but the situation has changed. Specifically, the context attribute points to the input parameter (document at this time ). At present, I still do not understand the significance of assigning values to context attributes in such a large circle? The next question may be the difference between $ (document). ready and window. onload? The definition of the extract ready function is as follows: ready: function (fn) {// Add the callback jQuery. ready. promise (). done (fn); return this ;}, reading the code to explore promise is a bit dizzy, think of your iJs toolkit, print jQuery. ready. promise () is as follows: [Object] jQuery. ready. promise () | -- [function] always | -- [function] done | -- [function] fail | -- [function] pipe | -- [function] progress | -- [function] promise | -- [function] state | -- [function] then to further print and sort out the done function Code as follows (this completely halts ~~): Function () {if (list) {// First, we save the current length var start = list. length; (function add (args) {jQuery. each (args, function (_, arg) {var type = jQuery. type (arg); if (type = "function") {if (! Options. unique |! Self. has (arg) {list. push (arg) ;}} else if (arg & arg. length & type! = "String") {// Inspect recursively add (arg) ;}) (arguments ); // Do we need to add the callbacks to the // current firing batch? If (firing) {firingLength = list. length; // With memory, if we're not firing then // we shocould call right away} else if (memory) {firingStart = start; fire (memory );}} return this;} fortunately, the Code is not long. It seems that the key lies in the fire function. Well, I found myself awake. In the preceding done function, we can note that the default arguments variable is used to push the injected function to the list array. The following is the fire function: fire = function (data) {memory = options. memory & data; fired = true; firingIndex = firingStart | 0; firingStart = 0; firingLength = list. length; firing = true; for (; list & firingIndex <firingLength; firingIndex ++) {if (list [firingIndex]. apply (data [0], data [1]) ===false & options. stopOnFalse) {memory = false; // To prevent further callusing add break;} firing = False; if (list) {if (stack. length) {fire (stack. shift () ;}} else if (memory) {list = [];} else {self. disable () ;}}you can see that the application is used in the list array in the code. When debugging with the iJs package, we can find that data [0] is a document object. That is to say, the result of calling $ (myFunction) Is that myFunction is executed on the document object. Because list is an array, it is difficult to understand that $ () is actually input multiple times and executed once. Finally, let's look back at the promise source code. The secret about the execution time of the $ () input function is here: jQuery. ready. promise = function (obj) {if (! ReadyList) {readyList = jQuery. deferred (); // Catch cases where $ (document ). ready () is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if (document. readyState = "complete") {// Handle it asynchronously to allow scripts Opportunity to delay ready setTimeout (jQuery. ready, 1); // Standards-based browsers support DOMContentLoaded} else if (document. addEventListener) {// Use the handy event callback document. addEventListener ("DOMContentLoaded", DOMContentLoaded, false); // A fallback to window. window. addEventListener ("load", jQuery. ready, false); // If IE event model is used} else {// Ensure firing befor E document. attachEvent ("onreadystatechange", DOMContentLoaded); // A fallback to window. window. attachEvent ("onload", jQuery. ready); // If IE and not a frame // continually check to see if the document is ready var top = false; try {top = window. frameElement = null & document.doc umentElement;} catch (e) {}if (top & top. doScroll) {(function doScrollCheck () {if (! JQuery. isReady) {try {// Use the trick by Diego Perini // the http://javascript.nwbox.com/IEContentLoaded/ top. doScroll ("left");} catch (e) {return setTimeout (doScrollCheck, 50);} // and execute any waiting functions jQuery. ready () ;}}) () ;}} return readyList. promise (obj) ;}; from the comments of the code, we can see that this code has paid a lot of attention in the process of eliminating bugs. View one of the URLs http://bugs.jquery.com/ticket/12282?comment:15, which is a bug related to ie9/10( document ready is fired too early on IE 9/10). Fortunately, it has been solved. The whole thing looks like this. If every browser has document. readyState = "complete", it's easy. As you can see $ (), I would like to thank the great gods who wrote jQuery (and other similar frameworks) for their efforts to make the world perfect.

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.