Is it really necessary to wait for the \"ready\" (or \"window.onload\") events if your code only manipulates DOM elements that have already been parsed entirely?
The
Document is loaded in linear fashion so your code works correctly. Sometimes programmers do not use document ready for performance purpose when the javascript is not depends on the DOM below it. Here is some example.
Yes, it's safe if you js code is after dom but usually it's not relly good idea to mix html and js.
If your JavaScript code is below the DOM elements and only modifies them exclusively, you don't need to wait for the DOM ready event.
However, keep in mind editing a DOM element which contains a script
element (or more specifically, before the element's closing tag) used to cause big problems in IE6 (thanks T.J. Crowder) and IE7.
However, this requires inline scripts
which can be a maintenance problem. It is preferred to have your JavaScript stored externally (and many speak of the benefits of including them before the closing body
tag) for many benefits such as ease of maintenance and fine grained cache control.
in your case it is fine because the browser will render your code line by line and in your code id="foo" comes first so it will get that div....but suppose you wrote this script in head tag then the script will run first and it wont get the div with id="foo" because its not yet loaded..its better to write in document.ready method