Llamar a una función en un script que se incluye dos veces en una página

Today, I read a question about the danger in including the same JavaScript library twice. I created a small project to test that with a simple alert in a function called on the click of a link. I used jquery to help me binding an event handler to the click like that:

Caso 1

JavaScript:

$(document).ready(function () {
    $("#TestLink").click(function() {
        alert("Message");
    });
});

HTML:

<p>
   <a id="TestLink">Click here</a>
</p>

Now, when I click on the link, the message is displayed twice. I understand that jquery bind an event handler twice because the reference to the script has been added twice.

In another case, I change the code to looks like that:

Caso 2

JavaScript:

function showMessage() {
    alert("Message");
}

HTML:

<script type="text/javascript" src="@Url.Content("~/Scripts/Test.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/Test.js")"></script>

<p>
   <a onclick="showMessage();" id="TestLink">Click here</a>
</p>

When I click on the link, the message is just displayed once even if I included the script twice.

Mis preguntas:

In the case 1, how the process of binding an event handler twice is done when the same script is added more than once? I just want more details about the hook of events when a the same script is added more then once; articles, references, etc...

In the case 2, how the browser resolves the conflict having to choose which script to used for calling the function?

preguntado el 31 de julio de 12 a las 15:07

1 Respuestas

In the first case, the event is binded twice. It is sometimes desireable to do so. If you want a click event on a div, and another click event on the same div that isn't related, you might want both functions to execute. That's why both click events will fire and the functions called. In this case, it's the same function that is called twice! An example of a useful scenario for binding two functions on an event:

You might want to know whether a user is active. A click event on the body will tell you so. But, if an overlay is active, you want to remove the overlay. Both functions are executed on the click event on the body.

In the second case, the function you declared in the first include of the javascript is overwritten by the same function in the second javascript. The first declaration is gone. The function is therefore just called once:

var test = function() {
  alert('first one!');
}
var test = function() {
  alert('second one!');
}
test(); // second one!

Respondido 31 Jul 12, 15:07

+1. In case 2 there is no conflict to resolve; the second declaration of showMessage overwrites the first, so there's only one showMessage for the javascript engine to choose from. - Chris

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.