Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefits of loading JS at the bottom as opposed to the top of the document

What are the real benefits (if any) to loading your JS at the bottom of the document, as opposed to the top. It seems there is a brief delay in page loading and JS dependent functionality.

I am using html5boilerplate for beginning all my templates, but am not really sure on how beneficial loading the JS at the bottom is.

Does it really make all that much of a difference, and if so, why?

like image 641
jeffreynolte Avatar asked Mar 16 '11 18:03

jeffreynolte


People also ask

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.

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.

Does the order of JavaScript files matter?

If I'm understanding your question I think you're asking if it matters where in a file a function/method is defined, and the answer is no, you can define them anywhere in a single source file. The JavaScript parser will read in all symbols before trying to run the code.

When should JavaScript be loaded?

If you need the functionality incorporated in the script or scripts, like function libraries, available before or during page loading then you should load JavaScript code in the head tag.


2 Answers

  1. If you include external js files at the bottom of your page, you give the priority of your HTTP requests to the visual display that will be presented to the client instead of to the logic of interaction or dynamics. I believe, if you do not use a content delivery network to deliver images to the client then you are only allowed to process a maximum of 2 HTTP requests at a time. You do not want to waste these requests on logic because we all know how impatient the end user is.

  2. By loading js at then end of the file you can access the DOM(most of the time) without having to call a document.ready() function. You know that if the page render finally makes it to your javascript code that the necessary page elements have usually loaded already.

There are a few more reasons out there but these are the important ones that I try to remember when it feels so awkward to place all js at the bottom.

like image 138
Tim Joyce Avatar answered Sep 23 '22 08:09

Tim Joyce


As scripts that are referred to are being downloaded, browsers typically won't download other files in parallel, thus slowing the page load.

refer: Best Practices for Speeding Up Your Web Site

like image 36
Adam Price Avatar answered Sep 19 '22 08:09

Adam Price