something

JS execution order 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 executing inline js code, somefile.js is loaded, so it can work with the div in front of it?

+5
source share
1 answer

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

The DOM, however, is not ready yet, so you cannot access the div. If you want to do this, 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 greatly simplifies it, you just write

$(function() {
   // inline code ...
});
+3
source

All Articles