Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why scripts at the end of body tag

Tags:

I know this question was asked many times, but I haven't found answer. So why its recommended to include scripts at the end of body tag for better rendering?

From Udacity course https://www.udacity.com/course/ud884 - rendering starts after DOM and CSSOM are ready. JS is HTML parse blocking and any script starts after CSSOM is ready.

So if we got:

<html>     <head>         <meta name="viewport" content="width=device-width,initial-scale=1">         <title>CRP</title>         <link rel="stylesheet" href="styles.css">     </head>     <body>         <!-- content -->         <script src="script.js"></script>     </body> </html> 

CRP would be:

CSSOM ready > JS execute > DOM ready > Rendering 

And if script is at head:

<html>     <head>         <meta name="viewport" content="width=device-width,initial-scale=1">         <title>CRP</title>         <link rel="stylesheet" href="styles.css">         <script src="script.js"></script>     </head>     <body>         <!-- content -->     </body> </html> 

CRP would be the same:

CSSOM ready > JS execute > DOM ready > Rendering 

This question is only about "sync" scripts (without async/defer attribute).

like image 688
Artem Svirskyi Avatar asked Jun 04 '15 20:06

Artem Svirskyi


People also ask

Why might you place a script tag at the end of the body tag rather than at the end of the head?

It helps because the HTML page isn't rendered only after the DOM is ready: the browser starts rendering the page as it parses the DOM. This means that you can achieve a faster "load" of the page (even though the DOM isn't ready) by making the browser load the scripts last.

Do scripts go inside the body tag?

JavaScript in body or head: Scripts can be placed inside the body or the head section of an HTML page or inside both head and body.

Should scripts be inside or outside body?

Always end with a body tag and make sure every single JavaScript part is within the body tag. You can also have links or scripts inside head tags, but it is not recommended unless you are really certain your JavaScript code is too big to have it inline.

Where should I put script tags?

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.


1 Answers

Scripts, historically, blocked additional resources from being downloaded more quickly. By placing them at the bottom, your style, content, and media could download more quickly giving the perception of improved performance.

Further reading: The async and defer attributes.

like image 148
Sampson Avatar answered Oct 08 '22 12:10

Sampson