3

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

    ...
2
  • probably you can set a flag on dom load and check that flag to see whether dom has loaded Commented May 20, 2013 at 5:41
  • Actually, my javascript code comes into page at runtime So I can't bind events on document.ready. I just needed to check some boolean variable kind of thing which Yeahman has answered. Commented May 20, 2013 at 5:53

3 Answers 3

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

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.

0
2

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
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.