tags:

views:

59

answers:

2

1.

<div id="test"></div>
<script type="text/javascript">
//operate document.getElementById('test')
</script>

2.

<div id="test"></div>
<script type="text/javascript">
window.onload = function()
{
  //operate document.getElementById('test')
};
</script>

Can we ensure that document.getElementById('test') exists just by putting javascript below it?

+5  A: 

In my subjective testing, it does always work that way, yes. The DOM is parsed in order from top-to-bottom on the page, so if your script tag is below the element you're targeting it will load in order and work.

The window.onload is useful in situations where your script is located in the head of the file, loaded from an external file or otherwise might not be appropriate inline in the page like that.

Gabriel Hurley
A: 

http://developer.yahoo.com/yui/event/#onavailable

YUI allows you to define event handlers for onAvailable, onContentReady and onDOMReady instead of window.onload

These methods will execute before window.onload fires

Also onDOMReady is a safer place for code such as this because it will prevent some bugs from IE6 from happening. Adding DOM nodes while the DOM is still being constructed can cause some obscure bugs in IE.

<script type="text/javascript">

 function init() {
    //operate document.getElementById('test')
 }
 YAHOO.util.Event.onDOMReady(init);

 // As with addListener, onAvailable, and onContentReady, you can pass a data object and adjust the scope
 // YAHOO.util.Event.onDOMReady(init, data, scope);

 </script>
 <div id="test"></div>