Dan Abramov Dan Abramov - 6 months ago 35
Javascript Question

How do I know when DOM “body” element is available?

As soon as

DOM node is available, I'd like to add a class to it with JavaScript.

I want this to happen as soon as possible, before any of
's children are loaded.

Right now, I'm using an inline script right after opening
tag. Is there a less obtrusive way?


I would imagine this will differ between browsers.

One solution may be to test for it by placing a script immediately inside the opening <body> tag, then running your code at an interval to add the class.

    function add_class() { 
             document.body.className = 'some_class';
            setTimeout(add_class, 10);  // keep trying until body is available

    <!-- rest of your elements-->

jQuery does something similar internally to deal with a particular IE bug.

There isn't a guarantee that the descendant elements won't be loaded though, since again it will depend on when the particular implementation makes the body available.

Here's the source where jQuery takes a similar approach, testing for the existence of the body in its main jQuery.ready handler, and repeatedly invoking jQuery.ready via setTimeout if the body isn't available.

And here's an example to see if your browser can see the <body> element in a script at the top of the element, before the other elements. (Open your console)

Here's the same example without needing the console.