Possible Duplicate:
Where to place Javascript in a HTML file?
Should I write script in the body or the head of the html?
I've always wondered, mainly because when creating pages I always run into trouble, based on the following thing:
When do you write your javascript
<head>
<body>
$(document).ready()
I could be stupid, but I've had a few times when my JavaScript (/jQuery) wasn't executed because of the wrong place or yes or no doc.ready()
command. So I'm really wondering so.
Same goes for jQuery and 'var' command
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.
If your is not placed inside a function, or if your script writes page content, it should be placed in the body section. It is a good idea to place scripts at the bottom of the <body> element. This can improve page load, because script compilation can slow down the display.
If it's in the HEAD section, the script will be parsed before any HTML or CSS elements are loaded. If your Javascript references any of the web page's elements, there may be a slight delay in the fancy effects you want to apply, or it may just not work at all.
To avoid multiple server requests, group your JavaScript files into one. Whatever you use for performance, try to minify JavaScript to improve the load time of the web page. If you are using single page application, then group all the scripts in a single file.
$(document).ready()
simply ensures that all DOM elements are loaded before your javascript is loaded.
When it doesn't matter
Without waiting for this event to fire, you may end up manipulating DOM elements or styles that are yet to exist on the page. the DOM ready event also allows you more flexibility to run scripts on different parts of the page. For example:
<div id="map"></div> <script type="text/javascript">document.getElementById('map').style.opacity = 0;</script>
will run because the map div has been loaded before the script runs. In fact, you can get some pretty good performance improvements by placing your scripts at the bottom of the page.
When it does matter
However, if you are loading your scripts in the <head>
element, most of your DOM has not loaded. This example will not work:
<script type="text/javascript">document.getElementById('map').style.opacity = 0;</script> <div id="map"></div>
will not, since the map div has not been loaded.
A safe solution
You can avoid this by simply wait until the entire DOM has loaded:
<script type="text/javascript">$(document).ready(function () { document.getElementById('map').style.opacity = 0; }); </script> <div id="map"></div>
There are plenty of articles that explain this, as well as the jQuery documentation itself.
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