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?
The best practice is to put JavaScript <script> tags just before the closing </body> tag rather than in the <head> section of your HTML. The reason for this is that HTML loads from top to bottom. The head loads first, then the body, and then everything inside the body.
By placing the JS at the bottom of your page before the closing </body> tag, you are allowing the HTML to be parsed prior to loading the javascript. This gives the effect of faster page load times.
Putting javascript at the bottom means that the other page content (text especially) loads before the javascript so users are not waiting for the JS to load if they have slow connections.
When a user requests a page from your site, the page HTML starts streaming to the browser. As soon as a browser encounters a tag for an external image, script, CSS file, etc., it will start downloading that file simultaneously. If you put your scripts at the bottom of a page, they'll be loaded last.
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.
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