Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it matter where JavaScript is placed on a html page?

Tags:

javascript

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.

like image 804
bplus Avatar asked Jul 22 '10 12:07

bplus


1 Answers

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).

like image 169
Nick Craver Avatar answered Nov 11 '22 12:11

Nick Craver