When do you put Javascript in body, when in head and when use doc.load?

Sander Schaeffer picture Sander Schaeffer · Jan 15, 2013 · Viewed 33.2k times · Source

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

  • In the <head>
  • In the <body>
  • with a $(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

Answer

Kyle picture Kyle · Jan 15, 2013

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