John
John

Reputation: 908

Executing JS before whole DOM is ready

Ok, I made 2 posts about this but somehow I can't get it into my little mind.

So I concluded that if we have something like this:

<script type="text/javascript" src="somefile.js"></script>
<script type="text/javascript">
func1();
</script>

and func1() is defined in somefile.js, it is guaranteed to run when browser reaches that inline .

However, what if I have a big page (not taking into account images etc, just html) that takes a few seconds to load and for DOM to become ready (as I understand the DOM becomes ready when the whole html code has been loaded and parsed) and I want some code to be executed and work on parts of the page that have been loaded while the rest of the big page is still loading?

For example something like:

<div id="div1">Some div where content will be inserted by the inline javascript below</div>
<script type="text/javascript"> notifyPartLoaded("div1"); </script>

^^ Does something like this exist?

Upvotes: 0

Views: 1246

Answers (1)

user113716
user113716

Reputation: 322612

I'm not certain what your question is, but a simple way to ensure DOM ready is to place your JavaScript at the bottom of the HTML, just in side the closing </body> tag.

<!doctype html>
<html>
    <head>
        <title>some title</title>
        <!-- this script could go toward the bottom too, but it must be before --> 
        <!--   your script if your script relies on it -->
        <script type="text/javascript" src="somefile.js"></script>
    </head>
    <body>  
        <div id="div1">Some div where content will be inserted by the inline javascript below</div>
        <!-- your HTML -->
        <!-- your HTML -->
        <!-- your HTML -->

        <!-- Place your script last -->
        <!-- ...though it would be better to have it in a separate file -->
        <script type="text/javascript"> notifyPartLoaded("div1"); </script>
    </body>
</html>

Because your code is after all the other elements, they will exist for manipulation when your code finally loads and runs.

Upvotes: 1

Related Questions