views:

563

answers:

5

I was just using the plugin "Yslow" for Mozilla Firefox and it told me that I should put JavaScript at the bottom. I have heard this before but haven't really thought about it too much. Is there really an advantage in putting JavaScript at the bottom of a web page compared to the top?

A: 

Yes, the page will load the content and render it before loading and executing javascript, and the page will, as a result, load faster.

CodeJoust
+2  A: 

Assuming you aren't running on a CDN or aren't serving your JS from a separate sub-domain or server, it will load synchronously and force your HTML content to wait until it has downloaded the files. By placing the JS at the bottom of your page before the tag, you are allowing the HTML to be parsed prior to loading the javascript. This gives the effect of faster page load times.

cballou
+5  A: 

It'll allow the web page to load visibly before executing JavaScript, which makes sense for things like Google Analytics, which don't need to happen before the page loads.

You may also want to look into things like jQuery, prototype, etc and attach to the "ready" handler, which executes JavaScript code after the DOM has been fully loaded, which is an appropriate place for much JavaScript code.

wojo
Does this mean that JavaScript that is usually within the <head></head> tags can be wherever in the page after the <body> tag?
Nate Shoffner
Yes, <script> tag can be anywhere and it will be executed when encountered, so there's a good chance that everything before it will already be visible to the user (but it is not guaranteed).
vava
You dont even have to put the script inside the html tags, you can put it outside at the bottom and it would still work... though it might look a little funny.
NickLarsen
Before going mostly event-driven with jQuery, I sprinkled script tags all around as vava and NickLarsen mentioned. They can be nearly anywhere in your HTML, even after the HTML tag.
wojo
@NickLarsen, this doesn't validate. Bad practice.
cballou
A: 

If you have static html content and a lot of javascript, it can make a difference in perceived page load time since the html will load first giving the user something to look at. If you don't have much javascript, or the existing page content relies on the javascript to be useful, then this is not as useful practically-speaking.

bmoeskau
A: 

What about if the Javascript is in a separate file?

I prefer this way, simply because it's easier to debug/read. Is this loading faster/slower?

Mark Kadlec