如何在不使用jQuery(替代方式)的情况下知道页面何时准备就绪?

Ito*_*Ito 31 javascript

可能重复:
$(document).ready等效没有jQuery

如果您在页面中调用了jQuery.你可以简单地做到:

$(document).ready(function() { /** code inside **/});
Run Code Online (Sandbox Code Playgroud)

但是没有jQuery怎么做类似的事情?

ale*_*lex 42

您可以使用该DOMContentLoaded活动.

document.addEventListener('DOMContentLoaded', function() {
   // ...
});
Run Code Online (Sandbox Code Playgroud)

请注意,在较旧的IE中,您需要解决方法,readystatechange如果我没记错的话,有些人会使用该事件.

  • 假设您不关心支持旧浏览器...... (6认同)

Sha*_*mer 15

我认为回答你问题的最简单方法是回答"jQuery如何做到这一点?" 为此,我建议将其视为源代码.代码中最相关的部分位于 https://github.com/jquery/jquery/blob/master/src/core.js#L423

这是一个片段:

// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
    // Handle it asynchronously to allow scripts the opportunity to delay ready
    return setTimeout( jQuery.ready, 1 );
}

// 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();
    }
}
Run Code Online (Sandbox Code Playgroud)