Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of JS execution in HTML pages

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?

like image 284
John Avatar asked Oct 11 '22 17:10

John


1 Answers

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 ...
});
like image 130
phihag Avatar answered Oct 13 '22 10:10

phihag