Does it matter where JavaScript is placed on a html page?
Question by bplus
I’ve messing about with html5, I’ve never really had a good look at JavaScript before.
I’m referencing script file like this (not in the head)
<script src="somthing.js"></script>
However the script only seems to work if it placed below certain elements on the page.
Are there particular situations when it matters where javascript is placed?
Thanks in advance.
Answer by Starx
Well, here is what I think.
If you need to execute your script, before the HTML starts the render in the clients browser then it will be better to be placed in <head>
section.
And if you are executing a JavaScript code which communicates with a element in some way then the script should be placed behind that element, because if the script starts ahead then it can’t find its respective element to communicate with. So it is better to placed behind element.