Pergunta

There is one question about jQuery and good using I am asking myself for a while. Is there a difference between setting an event handler through jQuery in $(documemt).ready() an setting it in HTML in the DOM event handler?

To make it a little bit clearer: I don't want longer loadtimes by adding many events to my site. An example: I want to add an ajax dropdown to display the new messages in my forum instead of just redirect to the inbox. I got two ways to do this.

• the jQuery way => $(documemt).ready()

$(document).ready(function () {
    $(".new_messages_link").click(function (e) {
        e.preventDefault();
        // Ajax query an showing the dropdown
    });
});

Just bind the event handler in jQuery, after the site is loaded. Probleme here is, that the the click only works after the site is fully loaded. A problem with large images, that slows the site down.

• the html DOM way

<a href="#" class="new_messages_link" onClick="show_new_messages(this); return false;">New Messages</a>
function show_new_messages(var element) {
    // Ajax query an showing the dropdown
}

This is no strict programming, you need to change the html, if you change the method, but you don't need to wait for $(documemt).ready(). Also there is no load during showing the site, just if you click, am I right?

The Problem:

So my question is, what should I use? What is better, what is the real difference? And for information, it is not just one event handler I want to set, there are many, so loading time is important. I am not sure, I have a bad feeling in putting too much code in $(documemt).ready() functions.

Foi útil?

Solução 3

Also there is no load during showing the site, just if you click, am I right?

Clicking the link will only work once the show_new_messages script has loaded, so your user might see an error message if you use the onclick attribute and they click on it before the script loads. Setting up the event handler in $(documemt).ready() means that by the time the event handler is attached, all of the scripts will have loaded too, so clicking on it will work.

Outras dicas

If you're going to use jQuery then you should use the $(document).ready(function(){}); method. This is called "Unobtrusive Javascript" and allows you to separate your business logic/behaviour from your presentation/markup.

(Just a note to say that by the $(document).ready(function(){}); method I'm actually more so referring to your event binding in your example)

http://en.wikipedia.org/wiki/Unobtrusive_JavaScript

Using inline scripting might be slightly faster but $(documemt).ready() approach is more reliable and it helps you to maintain the code by providing a separation layer between HTML & JS.

Note: Inline functions might still not be available on page load if related script has not been loaded yet. This might lead to unexpected behaviour or errors.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top