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.
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.
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.
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.
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.
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).
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