When do you put Javascript in body, when in head and when use doc.load? [duplicate]
Asked Answered
L

3

22

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

Lionfish answered 14/1, 2013 at 23:4 Comment(3)
Well var is a thing that's seriously not like the others ...Tripartite
See this answerAntiphony
To Pointy, I've seen [var] written in the head and body too, so I wondered if there is any differences. Mark Schultheiss, I'm asking about the differences, not whether a piece of script should be in head or body. This is a little different. Thanks, though.Lionfish
L
17

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

Lens answered 14/1, 2013 at 23:9 Comment(1)
Where does loading it in an external stylesheet fall?Scull
T
12

By modern "best practice", it's like this:

  • Put scripts in the <head> when they should happen before the page starts being rendered. Examples are things like HTML 5 shim libraries or Modernizr.
  • Put scripts in "ready" handlers when there's limited control over how the script is imported. Things like utilities that can be included on a page to unobtrusively add features generally use "ready" handlers because they can't be sure of how they'll be used.
  • Put scripts at the end of the <body> if you can get away with it in all other cases.

Sometimes you end up with dependencies in pages that require things that you'd otherwise like to load at the end of the body element. That's an undesirable situation, but if you can't avoid it that can force scripts to be loaded in the <head> instead of at the end of the <body>.

It's good to load things at the end of the document because browsers evaluate the contents of <script> tags when they load them. (There are some "modern" ways to avoid this, but that's getting into more complicated territory.)

The decision of when to use "ready" handlers (or "load" handlers, for that matter) is a little different than the decision about where to put the <script> tag. If you've got intra-page widgets from a server-side template system that generate (undesirable, but what can you do?) jQuery references for example, then you need to import jQuery at the top of the page, even though other code may defer initialization to "ready" handlers. That is to say, the decision about when to use "ready" has to do with whether your script is willing to rely on being imported into a page at the right point, or if it wants to ensure that the right thing happens regardless of where its <script> tag is placed.

Tripartite answered 14/1, 2013 at 23:9 Comment(0)
B
7

It is a matter of when you need the code to be executed.

If you are going to manipulate the DOM tree (e.g. move elements around/ show-hide etc) and you put your code in the head of your document, your elements will not be there when your code is executed, therefore your code will not work.

In that case you can put your code in the head of your document and invoke it when the document DOM is ready, with $(document).ready()

Putting code at the end of your document is rarely necessary, one occasion I can think of is google plus +1 button, that requires you to place a script after the last +1 button, so you just stick it to the end of your document to be sure.

Byer answered 14/1, 2013 at 23:11 Comment(1)
I subscribe to this methodology. I know the "modern" way is to put JS files at the end of the body. But unless performance is mission critical or you're expecting your users to employ legacy hardware/software, there's nothing wrong with placing your JS files in the head. In fact, the users may not even notice any performance difference. For maintenance and cleanliness, I prefer to keep JS files in the head or load them asynchronously to the head. However, if the page employs only vanilla JS, I may load the JS files at the end of the body.Gusti

© 2022 - 2024 — McMap. All rights reserved.