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.
If the script isn't waiting for an onload
or "ready" event of some sort, it needs to be place after the elements it references (otherwise they won't be there to find). If you're unsure, stick it just before </body>
.
In this case it looks like that's exactly what's happening, it's looking for elements that haven't been added to the DOM yet. Placing the script at the bottom of the <body>
is one common practice to counter this. Some alternatives are using the window.onload
event to run your code, or jQuery's $(document).ready()
for example (most major libraries have some equivalent of this).
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