An in-depth analysis of how the ready function of jquery works (how it works) _jquery

Source: Internet
Author: User
Tags time interval ticket

This article is an in-depth analysis of how jquery's ready function works. Share to everyone for your reference, specific as follows:

JQuery is a great script library that was released by John Resig on the BarCamp NYC in January 2006. You can download to the latest version in http://jquery.com/and have been updated to the jquery 2.1.4 version as of this release. Here take jQuery1.8.3 as an example to analyze.

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 registers functions that can be executed when the page is ready.

The question is, when is our page ready?

1. OnLoad incident

The most basic way to deal with the page is the OnLoad event, we handle this event, there can be a variety of ways, that is, through the HTML, directly written in the BODY element in the beginning of the tag, you can use the event registration method to use, which can be divided into DOM0 and DOM2 way. Again, consider the compatibility of the browser, using the DOM2 method to write out, 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 ("onload", Jquery.ready);
}

2. The domcontentloaded incident

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

In addition to the well known onload events, and similar to the onload events in the DOM, we have domcontentloaded events to consider, and the standards-based browsers support this event, which triggers the event when all the DOM parsing is complete.

In this way, we can also register the handling of this event for standards-based browsers. In this way, we might capture the events that were loaded to completion earlier.

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

3. The onReadyStateChange Incident

What about the nonstandard browsers?

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

However, this event is unreliable, such as when there is a picture in the page, it may be triggered after the OnLoad event, in other words, it can only be executed 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" , domcontentloaded, false);
  A fallback to window.onload, that would 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
  doc Ument.attachevent ("onReadyStateChange", domcontentloaded);
  A fallback to window.onload, that would always work
  window.attachevent ("onload", Jquery.ready);
}

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

domcontentloaded = function () {
  if (document.addeventlistener) {
    Document.removeeventlistener (" Domcontentloaded ", 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 obscure, when the page DOM is not loaded, an exception is generated when the DoScroll method is invoked. Then we use the reverse, if not abnormal, then the page DOM loading is complete!

Diego Perini in 2007, reported a way to detect whether IE was loaded, using the DoScroll method to invoke. See here for a detailed description.
The principle is that in the case of IE in the non-IFRAME, only through the ability to perform doscroll to determine whether the DOM has been loaded. In this example, try to execute doscroll every 50 milliseconds, note that because the page is not loaded, calling DoScroll causes an exception, so Try-catch is used to catch the exception.

(function Doscrollcheck () {
  if (!jquery.isready) {
    try {
      //use ' Trick by Diego Perini
      //HTTP://JAVASC ript.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 is too late, the page has been loaded, we only register their own ready function, then do not need to check the layer above, directly to see the current page of the readyState can be, if it is complete, Then we can directly execute the READY function we are going to register. However, Chriss reported a very special error situation, we need to delay execution.

SetTimeout is often used to make a timer on a Web page, allowing it to be given a millisecond number for the duration of the interval. When the program being started needs to run in a very short time, we're going to give her a very small amount of time, or we need to do it right away, we even set this millisecond to 0, but in fact, SetTimeout has a minimum execution time, and when the time specified is less than that, The browser uses the minimum allowable time as the settimeout interval, which means that even if we set the settimeout milliseconds to 0, the invoked program does not start immediately.

How much is the minimum time interval? This is related to the browser and the operating system. In John Resig's new book, "The Secret of the JavaScript ninja," it says

Browsers all have a 10ms minimum delay on OS X and a (approximately) 15ms delay on Windows. (The minimum time interval on the Apple machine is 10 milliseconds, the smallest on the Windows system The time interval is approximately 15 milliseconds, and in addition, 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 using settimeout is no way to shorten the minimum time interval.

So, by setting it to 1, we can have the program run after the minimum time interval that the browser supports.

Catch cases where $ (document). Ready () is called after the browser event has already.
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") {
  //delay after 1 milliseconds, execute ready function
  settimeout (jquery.ready, 1);
}

6. Complete code

The complete code in JQuery is shown below. #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.  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 ASYNCHR
    onously to allow scripts of opportunity to delay ready (settimeout, 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 would 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 would always work window.attachevent ("onload", Jquery.ready);
      If IE and not a frame//continually check to-if the document is ready var top = false;
      try {top = Window.frameelement = null && document.documentelement; The catch (e) {} if (top && top.doscroll) {(function Doscrollcheck () {if!jquery.isread Y) {try {//use ' Trick by Diego Perini//Http://javascript.nwbox.com/IECont
            Entloaded/top.doscroll ("left");
            catch (e) {return settimeout (Doscrollcheck, 50);
          }//and execute any waiting functions jquery.ready ();
      }
        })();
}} return Readylist.promise (obj);

 };

So, who is to call it? Of course it is necessary, when we call the ready function, we need to register these to determine whether the page is fully loaded processing, this code in the 1.8.3 in the code #244 line, as follows:

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

After referencing the jquery script library on the page, the initialization function of jquery was performed, and the Ready function was created in the initialization function. JQuery completes the registration of the page detection code before we register the event processing via the Ready function. Such When the page is fully loaded, our registered function is invoked.

Add: jquery Ready Shorthand mode

Jquery Ready function:

$ (document). Ready (function () {
  alert (' I am ready ');
}
);

can be abbreviated as:

$ (function () {
  alert ("I am in");
}
);

I hope this article will help you with the jquery program design.

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.