Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference when including <script> tag in HTML's header or body

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?

like image 988
tzador Avatar asked Nov 10 '10 15:11

tzador


People also ask

Does it matter if script is in head or body?

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.

What is difference between script tag in head and body?

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.

What is the difference between body and header in HTML?

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.

Where should I put my script tag in HTML?

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.


1 Answers

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.

like image 139
Matthew Jones Avatar answered Oct 04 '22 00:10

Matthew Jones