Research on source code of jquery ready Function

Source: Internet
Author: User

Generally, the onload of the Body Tag is set to listen to the load event of the window. however, the load event is triggered only after all the elements on the page are loaded. If there are too many pages or the picture is too large, it will lead to initialization. Code When not executed, the user performs other operations. the jquery Library provides a very convenient and useful function ($ (selector ). ready (), so that we can perform corresponding operations after the DOM of the page is loaded (of course, it depends on the support of the user's browser )., instead of waiting for all elements to be loaded. for example:
$ (Document). Ready (function () {alert ('use in page script tag ')});
$ (Document). Ready (function () {alert ('use in import JS file ')});
Now let's take a look at the implementation of this function.
Principle:
When the jquery script is loaded, an isready flag is set to listen to the domcontentloaded event (this is not available in all browsers. jquery works differently in different browsers ). of course, when calling the ready function, if isready is not set, it means that the page is not loaded, and the function to be executed will be cached in an array. After the page is loaded, then execute the cached functions one by one.
Detailed code analysis in jquery:

Copy codeThe Code is as follows: Ready: function (FN ){
// Bind the listener
Bindready ();
// If Dom loading is complete
If (jquery. isready)
// Run this function immediately
FN. Call (document, jquery );
// Otherwise, save it
Else
// Add the function to the cache Array
Jquery. readylist. Push (function () {return fn. Call (this, jquery );});
Return this;
}

Let's take a look at jquery's bindready () function for notifications of Dom loading completion in different browsers:

Copy code The Code is as follows: var readybound = false;
Function bindready (){
If (readybound) return;
Readybound = true;

// Mozilla, opera, and webkitnightlies support domcontentloaded events
If (document. addeventlistener &&! Jquery. browser. Opera)
// Directly use Event Callback.
Document. addeventlistener ("domcontentloaded", jquery. Ready, false );

// If it is IE and is not embedded in the frame
// You need to constantly check whether the document has been loaded.
If (jquery. browser. MSIE & window = Top) (function (){
If (jquery. isready) return;
Try {
// Mark this place and parse it later (1)
Document.doc umentelement. doscroll ("Left ");
} Catch (error ){
/// Mark this place and parse it later (2)
SetTimeout (arguments. callee, 0 );
Return;
}
// And execute any waiting Functions
Jquery. Ready ();
})();

If (jquery. browser. Opera)
Document. addeventlistener ("domcontentloaded", function (){
If (jquery. isready) return;
For (VAR I = 0; I <document. stylesheets. length; I ++) // mark (3)
If (document. stylesheets [I]. Disabled ){
SetTimeout (arguments. callee, 0 );
Return;
}
// And execute any waiting Functions
Jquery. Ready ();
}, False );

If (jquery. browser. Safari ){
VaR numstyles;
(Function (){
If (jquery. isready) return;
If (document. readystate! = "Loaded" & document. readystate! = "Complete") {// mark (4)
SetTimeout (arguments. callee, 0 );
Return;
}
If (numstyles === undefined)
Numstyles = jquery ("style, link [rel = stylesheet]"). length;
If (document. stylesheets. length! = Numstyles) {// mark (5)
SetTimeout (arguments. callee, 0 );
Return;
}
// And execute any waiting Functions
Jquery. Ready ();
})();
}

// A fallback to window. onload, that will always work
Jquery. event. Add (window, "LOAD", jquery. Ready); // mark (6)
}
}

(1): This is mainly used to measure Dom ready under ie. the principle here is that trim ("Left") will cause an error. This tips will show you whether Dom has ready.
(2): setTimeout (arguments. callee, 0) indicates that the call is delayed by 0 seconds. In fact, it will not be called immediately, but will be called as soon as possible, it tells the browser to run the event handle for any pending event and update the current state of the document before calling. arguments. callee is the anonymous function of the outer layer. The caller of the Parameter
(3): You may find it strange. Why isn't it handled together by Mozilla? The reason is that after the domcontentloaded event of opera occurs, its CSS style is not fully available yet, so special processing is required to determine whether each CSS Tag is enable.
(4), (5): When the status of document. readystate in Safari is loaded or complete, the introduction of the CSS file fails to determine whether it is parsed. Therefore, you need to determine the number of CSS files.
(6): Finally, if none of the above hack is supported... Use the safest load event to ensure that the initialization code can be executed.

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.