Sachin Jain
Sachin Jain

Reputation: 21842

How to know if document has loaded

I have a piece of JS code which needs to determine if DOM has loaded. I know there are several ways of executing JS code when DOM has loaded like:

$(document).ready(function() { ... }); // Jquery version

document.body.onload = function() { ... } // Vanila JS way

I am looking for some method which looks like

function isDOMLoaded() {
    // Do something to check if DOM is loaded or not
    // return true/false depending upon logic
}

PS: Update (Post Answer Accept) I happen to see jquery also use the same approach to check if DOM has loaded. Take a look at the Implementation of jquery.ready() here

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();
    }

    ...

Upvotes: 3

Views: 15699

Answers (3)

user1693593
user1693593

Reputation:

You can use something like this

function isLoaded() {
    return (document.readyState === 'ready' ||
            document.readyState === 'complete')
}

Check for ready and complete status.

ready is only there for a short moment but do reflect when the DOM is ready. When the page is completely loaded however the status is changed to 'complete'. If you happen to check only for ready the function will fail, so we also check for this status.

Upvotes: 4

yeahman
yeahman

Reputation: 2767

function isDOMLoaded(){
 return document.readyState == 'complete';
}

Upvotes: 18

PSL
PSL

Reputation: 123739

How about this?

var flgDOMLoaded=false; //Set a global variable
 $(document).ready(function() { 
   flgDOMLoaded= true;
  // Some code
 });

function isDOMLoaded() {
   return flgDOMLoaded; // return it. 
  //You don't need this function at all. You could just access window.flgDOMLoaded
}

Upvotes: 2

Related Questions