Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

External JavaScript - body or head? [duplicate]

Tags:

Possible Duplicate:
Where is the best place to put <script> tags in HTML markup?

Where should I put my external JavaScript file? I know that people put it at the end of the body tag to make the web page look like it loads faster. But is there any cons about putting it at the end?

And would this be a good practice to put the JavaScript with the Google Analytics code?

<body> // Everything else over here ... conent etc..      <script src="myjavascript.js" type="text/javascript"></script>         <script type="text/javascript">         // google analytics code         </script> </body> 
like image 449
Jason Stackhouse Avatar asked Jul 18 '12 21:07

Jason Stackhouse


People also ask

Which is better option for JavaScript external link 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.

What is more appropriate way to include JavaScript as an external file?

Create external JavaScript file with the extension . js. After creating, add it to the HTML file in the script tag. The src attribute is used to include that external JavaScript file.

Is JavaScript written in head or 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.


2 Answers

Yes people usually put it at the end for faster page loads. What you have there with the google analytics script is common practice.

You might also want to check out head.js - this has been shown to be even faster than a single script put at the end of the body

like image 62
rgvcorley Avatar answered Sep 21 '22 20:09

rgvcorley


Current recommendations are to place the javascript at the bottom not because it "looks like it loads faster", but because by placing them there, javascript parsing and execution doesn't stop the browser from doing other things (like loading the rest of the page).

The one con I can think of is that if you define any objects and functions in external JS and want to use them in the page, you must wait for page load/ready.

As for the Google analytics code - it is good practice to place it at the bottom, as in your example.

like image 28
Oded Avatar answered Sep 19 '22 20:09

Oded