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?
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 ...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With