jQuery source code analysis (xviii) ready event Comments

When the event is ready to perform a function when the DOM document tree loaded (no images, css, etc.), so it's earlier than load trigger event. usage:

  • $ (Document) .ready (fun); fun is a function, which will be executed after the DOM tree is loaded when the anonymous function

ready to have a shorthand, can be directly passed $ (fun) can, because inside jQuey also defines a $ (document) jQuery object, and we are in the above wording is the same

ready event and the window's onload difference:

  • ready event; and so on dom tree can be performed after the upload is complete
  • onload event; after all the other web resources to load (including images, flash, audio, video) to perform   

onload event can also bind in a picture above, for example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
    <img src="https://www.cnblogs.com/images/logo_small.gif"  alt="">
    <script>
        $ (() => Console.log ( ' the DOM tree has been loaded ' ))                         // READY event 
        $ ( ' img ' ) .on ( ' the Load ' , () => console.log ( ' image has finished loading ' ))         // pictures load event 
        $ (window) .on ( ' the load ' , () => console.log ( ' resources have been loaded ' ))        // event after the completion of all resources to load pages         
    </ Script > 
</ body > 
</html>

Here we use the arrow functions to write code is very simple, we are bound in a ready event, onload event and the onload event on the window on a picture, after loading the output is as follows:

 First of all you can see is ready to trigger an event, then the picture of the onload event, and finally trigger onload event of the window, then all the resources are already over loaded

 

Source code analysis


 jquery's ready event on the document is bound to a DOMContentLoaded event object, he had a look at the package, the principle DOMContentLoaded event can look at to see this article describes, quite detailed: https://www.cnblogs.com /caizhenbo/p/6679478.html

jQuery's ready event is based on the list of functions you can see the list of functions implemented in this connection: https://www.cnblogs.com/greatdesert/p/11433365.html

When we call $ (fun) to perform a ready event when the first entry will be executed in the logic module associated with the ready as follows:

init: function( selector, context, rootjQuery ) {
    var match, elem, ret, doc;

    // Handle $(""), $(null), or $(undefined)
    if ( !selector ) {
        return this;
    }

    // Handle $(DOMElement)
    if ( selector.nodeType ) {
        this.context = this[0] = selector;
        this.length = 1;
        return this;
    }

    // The body element only exists once, optimize finding it
    if ( selector === "body" && !context &&the document.body) {
         the this .context = Document;
         the this [0] = the document.body;
         the this .selector = Selector;
         the this .length =. 1 ;
         return  the this ; 
    } 

    // the Handle the HTML strings 
    IF ( typeof Selector === "String " ) {
         / * slightly * / 
    } the else  IF (jQuery.isFunction (selector)) {             // If the parameter is a function selector, then that is ready to bind event 
        return rootjQuery.ready (selector);                     //Is performed rootjQuery.ready () method, and the selector as an argument 
    } 

    / * skip * / 
},

rootjQuery jQuery is internally defined a local variable, is a jQuery example, as follows:

= jQuery rootjQuery (document);                       // line 917, the stored document object reference example jQuery

Inlet module reference rootjQuery.ready () method is performed on the ready rootjQuery instance object (which is defined on the prototype), as follows:

= = jQuery.prototype jQuery.fn { 
    ready: function (the Fn) {
         // the Attach in the Listeners at The 
        jQuery.bindReady ();                  // first execution jQuery.bindReady () Binding ready event (in fact, the binding is DOMContentLoaded or onreadystatechange event) 

        // the Add at The callback 
        readyList.add (the Fn);                 // add a function for the function list readyList 

        return  the this ; 
    } 
}

jQuery.bindReady () is a static method for binding events, internal initialized readyList a jQuery.Callbacks ( "once memory") function object list

Then perform readyList.add (fn) fn save function to the function list readyList inside.

Achieve jQuery.bindReady () as follows:

jQuery.extend ({ 
    bindReady: function () {                             // Initialization ready event listener function list readyList, and bind the ready event listener primary function of the document object DOMContentLoaded 
        IF (readyList) {
             return ; 
        } 

        readyList = jQuery.Callbacks ( "Once Memory ");                         // call jQuery.Callbacks (flags) ready event listener function list readylist, while passing once and memory markers. 

        // Catch the WHERE $ Cases (the Document) .ready () Called the After at The IS 
        // Browser event has already occurred. 
        IF (document.readyState === "Complete") {                             // If the document is ready, then call jQuery.ready (wait) event listener ready to perform the function list readyList
            // the Handle IT asynchronously to the allow scripts at The Opportunity Delay ready to 
            return the setTimeout (jQuery.ready, 1);                                 // by setTimeout () asynchronous execution method jQuery.ready (wait), to allow other scripts ready delay trigger event. 
        } 

        // Mozilla, Opera and WebKit nightlies Rate this page Currently Support the this Event 
        IF (document.addEventListener) {                                      // bind DOMContentLoaded event in IE9 + and above browser 
            // the Use Event at The Handy callback 
            document.addEventListener ( "DOMContentLoaded", DOMContentLoaded, false ;)          // on the listener function DOMContentLoaded bound to the document object DOMContentLoaded events 

            // A fallback to window.onload, that will always work
            window.addEventListener( "load", jQuery.ready, false );

        // If IE event model is used
        } else if ( document.attachEvent ) {
            // 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 toplevel = false;

            try {
                toplevel = window.frameElement == null;
            } catch(e) {}

            if ( document.documentElement.doScroll && toplevel ) {
                doScrollCheck();
            }
        }
    },
    /**/
})

Here we call document.addEventListener bound DOMContentLoaded event on a document, such as DOM tree loaded after DOMContentLoaded will execute the function, defined DOMContentLoaded function is as follows:

IF (document.addEventListener) {          // If IE9 +, and other browser 
    DOMContentLoaded = function () { 
        document.removeEventListener ( "DOMContentLoaded", DOMContentLoaded, false );     // first remove the document DOMContentLoaded event of 
        jQuery.ready ();                                                                     // then call jQuery.ready () function event listener execution ready 
    }; 

} the else  IF (document.attachEvent) { 
    the DOMContentLoaded = function () {
         // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
        if ( document.readyState === "complete" ) {
            document.detachEvent( "onreadystatechange", DOMContentLoaded );
            jQuery.ready();
        }
    };
}

First will be removed in the event DOMContentLoaded function, and then call jQuery.ready () event, which is triggered events after the DOM tree (we performed readyList.add (fn in jQuery.fn.ready () inside) function will increase in turn trigger), as follows:

jQuery.extend ({ 
    the isReady: false , 
    ready: function (the wait) {                         // function to perform the actual trigger event listener ready ready event listener function function list readyList and data cache object. 
        // the Either A or the HOLD AN Released the domready / Event and Not yet READY Load 
        IF ((wait === true && -!! jQuery.readyWait) || (wait == true ! && jQuery.isReady)) {     // If true and the wait is equal to 0 jQuery.readyWait or wait is not true and false jQuery.isReady jQuery.isReady initialization is performed to false 
            // the Make Sure body EXISTS, AT Least, the gets IEs in Case a Little overzealous (Ticket # 5443). 
            IF (! the document.body) {
                 returnthe setTimeout (jQuery.ready,. 1 ); 
            } 

            // Remember that the DOM The IS ready 
            jQuery.isReady = to true ;                                         // set jQuery.inReady true, indicating ready event is ready. 

            // the If the DOM the Ready A Normal Event fired, Decrement, and the wait need BE IF 
            IF (the wait ==! To true && --jQuery.readyWait> 0 ) {
                 return ; 
            } 

            // the If there Functions are bound, to Execute 
            readyList.fireWith (the Document, [jQuery]);                  // execute ready event listener function readyList, context is a document (ie keyword this), [jQuery] is a parameter ready event listener function.

            // Trigger any bound ready events
            if ( jQuery.fn.trigger ) {
                jQuery( document ).trigger( "ready" ).off( "ready" );
            }
        }
    },
    /**/
})

 writer by: Desert QQ: 22969969

Last call readyList.fireWith () method to trigger off the back of each function in the function list.

 

Guess you like

Origin www.cnblogs.com/greatdesert/p/11720567.html