July 22, 2010

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.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!