What is the difference in behavior / performance when including tag in body or head part of html document. Also i noticed that google analytics is usually embedded at the end of body. why is that?
When you place a script in the head section, you will ensure that the script is loaded before anyone uses it. Scripts in the body section: Scripts to be executed when the page loads go in the body section. When you place a script in the body section it generates the content of the page.
JavaScript in head: A JavaScript function is placed inside the head section of an HTML page and the function is invoked when a button is clicked. JavaScript in body: A JavaScript function is placed inside the body section of an HTML page and the function is invoked when a button is clicked.
A HTML file has headers and a "body" (payload) — just like a HTTP request. The <body> encapsulates the contents of the document, while the <head> part contains meta elements, i.e., information about the contents. This is (typically) title, encoding, author, styling etc.
The script tag should always be used before the body close or at the bottom in HTML file. The Page will load with HTML and CSS and later JavaScript will load.
Most of the time you want to include scripts at the bottom of the body section. The basic reason is to ensure that the page (and consequently the DOM) has fully loaded before any javascript is executed upon it.
Additionally, since downloading scripts blocks the browser from downloading anything else at the same time, the page will appear to load faster if the page elements are loaded before the script. However, unless you are a huge website that gets lots of traffic like Yahoo or Google, you probably do not need to consider this.
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