How does the ready function of jQuery work?

Source: Internet
Author: User


There are many ways to learn jquery, and today we start with the ready function of jquery. The code in this example comes from the JQuery script library.

If you have used jQuery, you must have used the ready function, which is used to register functions that can be executed when the page has been prepared.

The question is, when is our page ready?

1. OnLoad Event

The most basic processing is the page onload event, we can handle this event, there are many ways, that can be written in HTML, directly in the BODY element of the start tag, you can also use Event registration method to use, which can be divided into DOM0 mode and DOM2 way. Again, consider the compatibility of the browser and write it out using the DOM2 method, as shown below.

if (Document.addeventlistener) {//A fallback to window.onload, that would always work window.addeventlistener ("load    ", Jquery.ready, false); If IE event model is used} else {//A fallback to window.onload, that would always work window.attachevent ("Onloa D ", Jquery.ready);}

2. domcontentloaded Events

However, the OnLoad event will not be triggered until all page elements have been loaded, including pictures on the page, and so on. If there are a large number of pictures on the page, the effect can be imagined, the user may not see the picture, it has started to operate the page, and then our page has not been initialized, the event has not been registered, this is not too late!

In addition to the well-known onload event, similar to the OnLoad event in the DOM, we also have the Domcontentloaded event to consider that the standard-based browser supports this event, which is triggered when all DOM parsing is complete.

In this way, we can also register the handling of this event for standards-based browsers. In this way, we may have captured the event that the load completed earlier.

if (Document.addeventlistener) {//Use the handy event callback Document.addeventlistener ("domcontentloaded", Domco    Ntentloaded, false); A fallback to window.onload, that'll always work window.addeventlistener ("Load", Jquery.ready, false);}

3. onReadyStateChange Events

What about non-standard browsers?

If the browser has a Document.onreadystatechange event, when the event is triggered, it can be considered as a DOM tree if Document.readystate=complete is already loaded.

However, this event is unreliable, such as when there is a picture on the page, it may be triggered after the OnLoad event, in other words, it can only be performed correctly when the page does not contain binary resources or is very small or cached as an alternative.

if (Document.addeventlistener) {//Use the handy event callback Document.addeventlistener ("domcontentloaded", Domco    Ntentloaded, false);    A fallback to window.onload, that'll always work window.addeventlistener ("Load", Jquery.ready, false); If IE event model is used} else {//ensure firing before onload, maybe late but safe also for IFRAMEs DOCUMENT.A    Ttachevent ("onReadyStateChange", domcontentloaded); A fallback to window.onload, that'll always work window.attachevent ("onload", Jquery.ready);}

What does the domcontentloaded function do? Finally, you will call the Jquery.ready function.

domcontentloaded = function () {if (Document.addeventlistener) {Document.removeeventlistener ("Domcontentload        Ed ", domcontentloaded, false);    Jquery.ready ();        } else if (document.readystate = = = "complete") {//we ' re here because readyState = = = "complete" in Oldie        Which is good enough for us-to-call the DOM ready!        Document.detachevent ("onReadyStateChange", domcontentloaded);    Jquery.ready (); }}

4. DoScroll Detection method

One of MSDN's methods for JScript is that when the page DOM is not loaded, an exception is generated when the DoScroll method is called. Then we use the reverse, if not abnormal, then the page DOM loading is complete!

Diego Perini, in 2007, reported a way to detect if IE was loaded, using DoScroll method invocation. See here for detailed instructions.
The principle is that for IE in non-IFRAME, only continuously through can execute doscroll to determine whether the DOM is loaded. In this example, try to execute doscroll every 50 milliseconds, noting that the call to DoScroll causes an exception because the page is not loaded, so try-catch is used to catch the exception.

(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);    }//and execute any waiting functions jquery.ready (); }})();

5. Document.readystate Status

If we register the ready function The point of time is too late, after the page has been loaded, we register our own ready function, then we do not need the above layer check, directly to see the current page readyState, if it is already complete, Then you can directly execute the READY function that we are going to register. But Chriss has reported a very special error situation, and we need to delay execution.

settimeout is often used to make a timer on a Web page, allowing it to specify a number of milliseconds as the time of the interval execution. When the program being launched needs to run in a very short period of time, we will give her a small amount of time, or need to execute immediately, we even set this number of milliseconds to 0, but in fact, SetTimeout has a minimum execution time, when the specified time is less than the time, The browser uses the minimum allowable time as the settimeout interval, which means that even if we set the number of milliseconds for settimeout to 0, the called program does not start immediately. What is the minimum time interval for

? This is related to the browser and operating system. In John Resig's new book, "The Secret of JavaScript Ninja", mentions

    Browsers All has a 10ms minimum delay on OSX and a (approxi mately) 15ms delay on Windows. (The minimum time interval on an Apple machine is 10 milliseconds, the minimum time interval on a Windows system is approximately 15 milliseconds)

, and the MDC's introduction to SetTimeout also mentions that The minimum time interval (dom_min_timeout_value) defined in Firefox is 10 milliseconds, and the minimum time interval defined by HTML5 is 4 milliseconds. Since the specification is written in this way, it seems that the use of settimeout is no way to shorten the minimum time interval.

Thus, by setting to 1, we can have the program execute after the minimum time interval supported by the browser.

Catch cases where $ (document). Ready () was called after the browser event had already occurred.//we once tried to use re Adystate "Interactive" here, but it caused issues like the one//discovered by Chriss here:http://bugs.jquery.com/ticket/ 12282#comment:15if (document.readystate = = = "complete") {//Delay after 1 milliseconds, execute the Ready function SetTimeout (Jquery.ready, 1);}

6. The complete code

The complete code in JQuery is shown below. The #842 line in the JQuery 1.8.3 source code.

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 the 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.onload, that will always work             window. AddEventListener (  "Load", jquery.ready, false );         // If IE event model is used         } else {            //  ensure firing before onload, maybe late but safe also for  Iframes            document.attachevent (  " onReadyStateChange ", domcontentloaded );             // a fallback to window.onload, that will always work             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.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");                    &nbsP;    } catch (e)  {                              Return settimeout ( doScrollCheck, 50 );                         }                          // and execute any waiting functions                          jquery.ready ();                     }                 }) ();            }         }    }    return readylist.promise ( obj  );};

So, who's going to call it? Of course it is necessary that when we call the ready function, we need to register the processing of whether these judgment pages are fully loaded, and this code is in the #244 line of code in 1.8.3, as follows:

Ready:function (FN) {//ADD the callback JQuery.ready.promise (). Done (FN); return this;}

After the jquery script library is referenced on the page, a jquery initialization function is executed, and the ready function is created in the initialization function. JQuery completes the registration of the page detection code before registering event processing with the Ready function. Such When the page is fully loaded, the function we have registered is called.


How does the ready function of jQuery work?

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.