5

Say I have something like this

<script type="text/javascript" src="somefile.js"></script>
<div>something</div>
<script type="text/javascript">
// Some INLINE javascript
</script>

Is it guaranteed (by all browsers) that when the inline js code is executed both somefile.js has been loaded AND it can operate on the div before it?

John
  • 898
  • 2
  • 9
  • 25

1 Answers1

4

It is guaranteed that you can access code from somefile.js.

The DOM, however, is not yet ready at this moment, so you cannot access the div. If you want to do so, use the following construct:

<div>something</div>
<script type="text/javascript">
// document.write calls go here, not in onReady

function onReady() {
    document.getElementsByTagName('div')[0].setAttribute('class', 'loaded');
    // Or other inline JavaScript
}

if (document.addEventListener) {
    document.addEventListener('DOMContentLoaded', onReady, false);
} else {
    window.onload = onReady;
}
</script>

jQuery significantly simplifies it, you'd just write

$(function() {
   // inline code ...
});
phihag
  • 278,196
  • 72
  • 453
  • 469
  • I cannot access the div from somefile.js or from the inline – John Jun 18 '11 at 13:40
  • @John you can, but only in a callback function that gets fired once the DOM is fully loaded. Updated with an example. – phihag Jun 18 '11 at 13:42