JQuery Ready Method implementation

Source: Internet
Author: User

Long ago left this problem, to catch up with 51 holiday, a good study to summarize it.

    1. First, the difference between the Ready method in JQ and the OnLoad method of window is mentioned here, first of all, just the DOM tree loaded, some IMG and other resources may not have been loaded, and onload is all loaded successfully. And the Ready method can have multiple, and the onload can only write one. There is another difference is what, think up to fill up.

    2. In general let's hand-write simulation of an JQ ready method, most of which I wrote:

  Document.ready = function (callback) {///compatible Ff,google if (Document.addeventlistener) {Document.addeventlistener (' domcontentloaded ', function () {document.                            RemoveEventListener (' domcontentloaded ', Arguments.callee, false);                        Callback (); }, False)}//compatible with IE else if (document.attachevent) {Document.atta                                Chevent (' onreadystatechange ', function () {if (document.readystate = = "complete") {                                Document.detachevent ("onReadyStateChange", Arguments.callee);                       Callback ();            }})} else if (Document.lastchild = = document.body) {callback (); }        }

First detect the Domcontentloaded event, and then revoke the binding, in the trigger callback, IE is to detect the onReadyStateChange event, if document.readystate = = "Complete" The old like the first to revoke the binding event, The final trigger callback, and finally a degenerate operation.

    1. The reason for the ready method is that the Window.onload event is triggered when all the resources on the page have been loaded. If resources such as large pictures on the page respond slowly, the Window.onload event can be delayed. So the DOM ready event occurs. This event is triggered after the DOM document structure is ready, that is, before the resource is loaded.

    2. Generally in mainstream browsers, domcontentloaded events are available on many WebKit browsers as well as IE9, and this event is triggered after the DOM document is ready to be included in the HTML5 standard. For browsers that support this event, using the Domcontentloaded event directly is the simplest and best choice. However, ie6,7,8 does not support domcontentloaded events.

In the above code that is written, the first detection is the Domcontentloaded event, and the old version of the browser or ie6-8, hack method is not known one:

    • ReadyState: If the browser has a Document.onreadystatechange event, when the event is triggered, it can be considered as if the DOM tree has been loaded when document.readystate=complete.
      eg
    //onreadystatechange event    document.onreadystatechange = function(e){        document.getElementById("divMsg").innerHTML += "<br/> onreadystatechange, readyState:" + document.readyState;         };
    • DoScroll detection: The Internet Explorer documentation shows that when the page DOM is not loaded, an exception is generated when the DoScroll method is called. (Microsoft's documentation indicates that DoScroll must be ready for the DOM main document before it can be triggered normally) then we use the reverse, if not abnormal, then is the page Dom loaded, you can continue to execute doscroll to determine whether the DOM is loaded
    //doScroll    var doScrollMoniterId = null;    var doScrollMoniter = function(){        try{            document.documentElement.doScroll("left");            document.getElementById("divMsg").innerHTML += "<br/>doScroll, readyState:" + document.readyState;            if(doScrollMoniterId){                clearInterval(doScrollMoniterId);            }        }        catch(ex){        }    }    doScrollMoniterId = setInterval(doScrollMoniter, 1);
    • SetTimeout: The function that is triggered in setTimeout must be triggered when the DOM is ready to complete.

      var setTimeoutReady = function(){document.getElementById("divMsg").innerHTML += "<br/> setTimeout , readyState:" + document.readyState;};var setTimeoutBindReady = function(){/in/.test(document.readyState)?setTimeout(arguments.callee, 1):setTimeoutReady();};setTimeoutBindReady();
    • External script: implemented by setting the Defer property of the script block. See: Links
    • Internal script: An improved version of the external script. External script requires the page to reference additional JS files. The internal script method can avoid this problem. See: Links

Some of the above methods actually have problems, such as the readystate status of complete when the picture has been loaded.
So the quote from a big guy is:

Specific use of DoScroll words last saw this way:

To ensure that the ready method is eventually called, the Load event will be bound to the ready method at the end of each of these methods. if (document.readystate = = = "complete") {//Handle it asynchronously to allow scripts the opportunity to delay REA    DY//The setTimeout here is for asynchronous SetTimeout (Jquery.ready, 1); standards-based browsers support domcontentloaded//Standard browser Listening event interface: Document.addeventlistener} else if (document.ad Deventlistener) {//Use the handy event callback Document.addeventlistener ("domcontentloaded", Domcontentload      Ed, false); A fallback to window.onload, that'll always work//article at the outset, here to ensure that it will trigger ready, so also for the onload also bind a callback Window.addev    Entlistener ("Load", Jquery.ready, false); If IE event model is used} else {//ie Listening event interface: document.attachevent//If there is a onreadystatechange event, listen//E Nsure firing before onload, maybe late but safe also for IFRAMEs document.attachevent ("onReadyStateChange", Domconte      ntloaded); A fallback to window.onload, that'll always work window. attachevent ("onload", Jquery.ready); http://javascript.nwbox.com/IEContentLoaded///See below description//If IE and not a frame//continually check to S      EE if the document is ready var top = false;      try {top = Window.frameelement = = null && document.documentelement;          } catch (e) {}//if it is IE and is not an IFRAME if (top && top.doscroll) {(function Doscrollcheck () { if (!jquery.isready) {try {//Use the trick by Diego Perini//Http://javascript . nwbox.com/iecontentloaded///Always call DoScroll scrolling, because DOM nodes are not doscroll methods until the DOM render is finished, so it will always be abnormal//until DOM rendering is over.            , this time the DoScroll method does not throw an exception and then calls $.ready () Top.doscroll ("left");            } catch (e) {return setTimeout (Doscrollcheck, 50);          }//and execute any waiting functions jquery.ready ();      }        })(); }    }

The code above implements such a process:

jquery source code implementation is slightly complex, and so on later analysis understand continue to add.

JQuery Ready Method implementation

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.