The order of execution of html/javascript , as far as I know , is serial (as in all programming language) , meaning the browser reads line by line of html/javascript code and interprets it .
That is why some javascript programmers put the tag at the end of the body – to make sure the entire DOM was loaded and they can now access whatever elements they want .
This is how they do it –
<html>
...
<body>
...
<script> //whatever code you want to put
</script>
</body>
I wanted to test this so I wrote the following code
<html>
<head>
</head>
<body>
<script>
var elm=document.getElementById("myp");
alert(elm.innerHTML);
</script>
<p id="myp"> well this is darned interesting </p>
</body>
</html>
As you can see I’ve put the script before the p element is defined and the script is trying to access it . I thought I would get an error since p isn’t supposed to be defined yet but I got “well this is darned interesting” (the value of p) .
The same thing happens when I put the script in the head element. (testest with chrome and firefox).
Can anyone shed some light into what’s going on ?
Putting aside the specifics of what’s going on with this particular example, I’ll summarize the general principle. My source is Flanagan, JavaScript: The Ultimate Guide, 5/e.
It’s too simplistic to think of a browser as reading a line of HTML and rendering something in response. Certainly it scans the input sequentially, but the sequence of DOM object construction is not line-for-line with the scanned input. Better to treat it as a black box.
If you want to run a script that will manipulate DOM elements, the safe and sure way is to run it as a handler for the
onloadevent. Sometimes you can write inline script to do it, but this is a gray area. Flanagan writes:However, you may need to manipulate the DOM after all the HTML has been parsed but before all images are loaded. If that’s your need, then a tool like jQuery and its
readyevent is the way to go.