Reputation: 152677
We can place JavaScript in 3 ways?
<head>
<body>
all methods are valid by W3C ?
So How to judge where JavaScript should be placed at bottom or which must be in <head>
or in <body>
?
<head>
,</body>
and<body>....<body>
for example: before any other XHTML
tag/code which are going to affect
with that JavaScript code.update: I saw mostly people use Google analytics code as a inline javascript at bottom?
Upvotes: 1
Views: 949
Reputation: 19334
I generally will place as much as I can into external js files. The main exception to this, is information injected into the page server-side at load. I tend to push everything that is not specific to the one page into a library/site js file. If you don't have a need for inline scripts (ie: document.write), then it's best to push your scripts to the bottom before the closing body tag (see YSlow and yahoo's research on why).
The primary reasons for this:
Upvotes: 0
Reputation: 10325
If you're concerned with page load times this google article on minimizing your payload size might help. I've linked to the section relating to deferring the loading of javascript. Not exactly what you asked for but might come in handy.
In fact, http://code.google.com/speed/ is just plain handy!
Upvotes: 0
Reputation: 38860
In my coding I follow the following rules with regards to JS organisation:
head
body
tagUpvotes: 6
Reputation: 25810
Related SO posts:
Where should I declare JavaScript files used in my page? In or near </body>
?
Does javascript have to be in the head tags?
Upvotes: 3
Reputation: 85792
In most all cases, Javascript should be as an external file, to allow caching and avoid re-downlading the exact same 100+-line script on each page load. (If, on the other hand, it is a script you only expect users to ever see once, then inline is fine.)
Whether or not it goes in head or body is really your choice, though Yahoo recommends the bottom of the body for performance.
Upvotes: 1