Skip to content Skip to sidebar Skip to footer

How To Know When Page Is Ready Without Using Jquery (alternative Way)?

Possible Duplicate: $(document).ready equivalent without jQuery If you have jQuery called in your page. You can simply do it: $(document).ready(function() { /** code inside **/}

Solution 1:

You can use the DOMContentLoaded event.

document.addEventListener('DOMContentLoaded', function() {
   // ...
});

Note that in older IEs you need workarounds, some use the readystatechange event if I recall correctly.

Solution 2:

I think the simplest way to answer your question is to answer "How does jQuery do it?" and for that, I'd recommend looking as the source code. The most relevant part of the code is at https://github.com/jquery/jquery/blob/master/src/core.js#L423

Here's a snippet:

// 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 readyreturnsetTimeout( jQuery.ready, 1 );
}

// Mozilla, Opera and webkit nightlies currently support this eventif ( document.addEventListener ) {
    // Use the handy event callbackdocument.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );

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

// If IE event model is used
} elseif ( document.attachEvent ) {
    // ensure firing before onload,// maybe late but safe also for iframesdocument.attachEvent( "onreadystatechange", DOMContentLoaded );

    // A fallback to window.onload, that will always workwindow.attachEvent( "onload", jQuery.ready );

    // If IE and not a frame// continually check to see if the document is readyvar toplevel = false;

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

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

Solution 3:

window.onload = function(){
 // do something
}

Solution 4:

Use below script:

<scripttype="text/JavaScript">functionfuntionToBeCalled(){
// code that will be exected after dom ready
}

window.onload=funtionToBeCalled;
</script>

Or there is one more way. Add onload event in body tag as below:

<bodyonload='functionToBeCalled();'></body>

Post a Comment for "How To Know When Page Is Ready Without Using Jquery (alternative Way)?"