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