views:

58

answers:

2

Hello everybody!

I have a very weird problem. I am using jQuery and i am using the $(function () to load functions when the dom is loaded. But with a unknown reason the code in the $(function () will run a second time. A preview is at: http://development.devhouse.nl/news/3/het-nieuwste-nieuwsbericht you will get 2 alert prompts, but there is only 1 written in a $(function () . The exact code is:

<script type="text/javascript">
        $(function () {
            alert('Test');
        });
</script>

And the whole source can be found here(open the source in your browser): http://development.devhouse.nl/news/3/het-nieuwste-nieuwsbericht

Please help me. I am hopeless....

Tom

+1  A: 
$().ready(function(){
     alert('Test');
});
Anantha Kumaran
+3  A: 

I suppose because the script is in your html body instead of in the head. Move it to the head, and it only fires once.

Is there a reason you have it there?

EDIT: For clarification, as Marcel Korpel noted, scripts can be nested in the body, and there can be performance reasons to have them at the end. But in this situation, the script was nested inside an element within the body. This works, but can lead to unexpected behavior if that element is manipulated in certain ways.

patrick dw
thank you! that is the anwser
Tom
Why is this? It shouldn't matter where a function resides, should it?
Marcel Korpel
@Marcel - Yes, you're right. Probably was something else going on that was manipulating that element, like `appendTo()`, or something. In any case, not the optimal place for your scripts.
patrick dw
@patrick: Hmm, first you say I am right, then you say "not the optimal place for your scripts." :P Well, it *is* when optimizing a page for speed: http://developer.yahoo.com/performance/rules.html#js_bottom
Marcel Korpel
@Marcel - In terms of the script running, you were right that it can be in the `body`. But not optimal in its placement in the middle of the `body` as the child of an `h1` element (or something). Bottom of the page (as your link suggested) would make more sense. I didn't mean optimal in terms of performance. More in terms of practicality (as the issue demonstrated).
patrick dw
@patrick: Ah, it was in the middle of an `h1`, I didn't notice that (and it was gone when the OP changed his page). Nonetheless, it's considered best practice to put your scripts in a separate file.
Marcel Korpel
@Marcel - Agreed. And I'll edit my answer with a clarification, as you brought up valid points.
patrick dw