Hi someTimesVarable, welcome to the forums,
Yes, I agree that learning can be a bit frustrating at times. Once someone knows so much, a lot of stuff seems obvious and mentionng it to "newbies" gets over-looked.
AFAIK, with most (all?) browsers, script in a page's head (that isn't in a function) runs when the head loads, before the rest of the page loads in. Ideally, code that needs the page to have been loaded will be in a function that gets called after the page finishes loading (or you can put the script at the bottom of the page's body, as you have learned
).
For example, if you put the snippet in a function in an external script
snippet.js
Code:
function list_item_alerts()
{
var listItems = document.getElementsByTagName("li");
for (var i = 0; i < listItems.length; i++)
{
alert(listItems[i].nodeName);
}
}
you could then do
HTML Code:
<script type="text/javascript" src="snippet.js"></script>
<script type="text/javascript">
document.onload = list_item_alerts();
</script>
I personally like all my script in external files called from the head, but I have read where some like larger/slower scripts in the end of the body instead. this is because script in the head can delay page loading. When it's in the end of the body, other page content (eg. text, images) can start to get rendered while the script finishes loading in.
In any case, I've found that the lessons I've learned the hard way "stick" better with me. I bet you won't forget this particular lesson too soon either.
Bookmarks