Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including JS in head or immediately after opening body tag

Tags:

javascript

What is the difference between including Javascript in the <head> as opposed to immediately after the OPENING <body> tag?

Facebook Like widget is one example where they suggest placing the code immediately after the opening <body> tag. SiteCatalyst also suggests this for their analytics code.

While there is an obvious difference between including the code in the <head> element as opposed to right before the closing </body> tag, I'm not sure what the difference is between the <head> and immediately after the opening <body> tag.

like image 865
Choy Avatar asked Mar 28 '12 21:03

Choy


People also ask

Should I put JS in head or body?

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 JavaScript go in the head tag?

You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code. The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load.

Where is the correct place to insert a JavaScript?

JavaScript in body or head: Scripts can be placed inside the body or the head section of an HTML page or inside Both the <head> section and the <body> section are the correct places to insert a JavaScript.

What happens if you place script elements in the head?

If it's in the HEAD section, the script will be parsed before any HTML or CSS elements are loaded. If your Javascript references any of the web page's elements, there may be a slight delay in the fancy effects you want to apply, or it may just not work at all.


1 Answers

If the JavaScript is outputting something into the DOM without a helper function (directly writing HTML), it would be important to have that JavaScript inside the <body>, however there should be no difference in this case wither it is right after <body> or right before </body>.

Typically, anything that is dependent on the DOM being loaded goes right before </body> because until the page renders to that point, it would be impossible for the full DOM to be loaded. My guess would be that these scripts don't depend on the DOM being loaded, but they do output HTML directly to the DOM (like a hidden <input> tag or something).

like image 128
Matthew Darnell Avatar answered Sep 28 '22 11:09

Matthew Darnell