views:

60

answers:

6

From the documentation I've found this example:

We can animate any element, such as a simple image:

<div id="clickme">
  Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />

With the element initially shown, we can hide it slowly:

$('#clickme').click(function() {
  $('#book').fadeOut('slow', function() {
    // Animation complete.
  });
});

I remember from 5 years ago, that you should NEVER ever refer to any element until it was defined. Does this rule still apply? So I would have to put all that code in the footer of my web page? Or can I put it in a separate file and import it in the footer? What's best practice?

+5  A: 

You are correct; you cannot interact with a DOM element before it exists.

You have two options:

  • Put the code below the HTML, as you suggested.

  • Put the code anywhere, but wrap it in $(function() { ... }).
    This construct will execute the function in the page load event, after the DOM exists.

SLaks
A: 

Many people put it in the bottom of the page so other code can execute first. That becomes a bit of a moot point with the document ready syntax that waits until other content loads to the dom. So, using that logic, in theory it could go anywhere.

bpeterson76
Still, if the script is at the bottom, the code is loaded last and the actual HTML page is rendered "faster".
Felix Kling
Splitting hairs quite a bit here. The difference would be almost unnoticeable I bet. Probably get a better speed gain optimizing and minifying than you'd notice doing this.
bpeterson76
+5  A: 

The recommended way of doing this is putting all initialization code into $(document).ready, like so:

$(document).ready(function() {
   $('#foobar').click(function(event) { alert("You Clicked Me!"); });
});
tdammers
I too prefer using `$(document).ready()` to the other style of invoking this, since it's more explicit.
Alex JL
+2  A: 

The best practice is to place all SCRIPT elements at the bottom of the HTML document (right before the </body> tag. The reasons are:

  1. loading of external JS files blocks loading of other resources (like images)
  2. since JS code is executed immediately, it is better to parse the HTML code of the page first, and then execute the JS code afterwards

You can see an HTML5 template that demonstrates this practice here: http://vidasp.net/HTML5-template.html

Šime Vidas
+1  A: 

Scripts go best in the foot of the page, to provide for the speediest rendering of the DOM. The following idiom executes only once the DOM is ready:

$(function() { /* ... your code goes here ... */ }

If you have a lot of code, or code that is shared between multiple pages, you should link it in a separate file which can then be minified, should you need to optimize your download speed.

David Eyk