How soon will jQuery(document).ready be called?

后端 未结 3 1027
情深已故
情深已故 2020-12-10 16:35

If a third party javascript file hangs and takes a while to load, will

jQuery(document).ready(function() {}) 

have to wait for that to

3条回答
  •  执笔经年
    2020-12-10 17:35

    Yes, it has to wait. In particular, you cannot rely on jQuery(document).ready() to fire before other scripts get a chance to execute. ready binds to DOMContentReady, readystatechanged, or onload, whichever is available.

    The documentation states that "in most cases, the script can be run as soon as the DOM hierarchy has been fully constructed". Note that the only guarantee is that the DOM is ready when this event fires. It does not guarantee you anything else - because it just cannot.

    This, for example will not work in IE, Firefox or Chromium, brilliant.js is always called before the ready() handler has a chance to execute no matter how you shuffle the script tags:

    
    
    
        Test
        
    
    
        
        
    
    
    

    FYI, here is the relevant code from jquery-1.4.2:

    bindReady: function() {
        if ( readyBound ) {
            return;
        }
    
        readyBound = true;
    
        // Catch cases where $(document).ready() is called after the
        // browser event has already occurred.
        if ( document.readyState === "complete" ) {
            return jQuery.ready();
        }
    
        // 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();
            }
        }
    },
    

提交回复
热议问题