How does jQuery's “document ready” function work?

前端 未结 3 1104
慢半拍i
慢半拍i 2020-12-05 00:12

How is jQuery checking if the document is loaded? How it is checking that the document load is finished?

3条回答
  •  忘掉有多难
    2020-12-05 00:43

    So there is a little bit going on behind the scenes but this is the gist of it, directly for the jQuery source:

    // Mozilla, Opera and webkit nightlies currently support this event
            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 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();
                }
            }
    

    So for most browsers (Mozilla, Opera and Webkit) there is a DOMContentLoaded event that jQuery is listening for, when that is triggered, then it calls all of the ready handlers you have registered with jQuery.

    IE acts a little differently as they don't have the DOMContentLoaded event, they try hooking into the onreadystatechange event of the document, they also hook up the window.onload event, as well as do a sneaky bit of code where they continuously try and scroll the page every millisecond (doScrollCheck). Which ever one of these fires first triggers the ready handlers and the subsequent events are ignored.

    I hope that makes sense and helps you out :)

提交回复
热议问题