Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript at bottom/top of web page?

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?

like image 953
user Avatar asked Oct 28 '09 17:10

user


People also ask

Should JavaScript be at top or bottom of page?

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.

How do I put JavaScript at the bottom of the page?

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.

Why JavaScript should be at the bottom?

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.

Why scripts are placed at bottom of the page?

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.


1 Answers

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.

like image 174
wojo Avatar answered Oct 03 '22 22:10

wojo