Better yet, use a jQuery handler?

I mean, if I have this handler:

$(document).ready(function() { $('.myElement').change(function() { // some }); }); 

linked to 400 elements, for example, it will be slower than

 function myFunct() { // some { <select class="myElement'" onchange="myFunct(this);return false"> // one of 400 elements. Each of this use that onchange link </select> 

because in fact I need to call this function only when I โ€œchangeโ€ something (so I donโ€™t understand why I need to process 400 elements, the worst of the resources).

What do you think about?

+4
source share
3 answers

Yes, it will be slower, since the browser must connect the handler of all these elements, which can cause a โ€œdelayโ€ in page loading, during which your user can interact with elements that do not have a handler code attached to them.

You can still use jQuery using only one delegated handler.

 $('#container').delegate(".myElement", "change", function () { myFuct(this); return false; }); 

Update! JQuery 1.7 example (using .on ):

 $('#container').on("change", ".myElement", function () { myFuct(this); return false; }); 
+7
source

Here you go:

 $(function() { function myFunct() { ... } $('.myElement').change( myFunct ); }); 

The trick is to define an object alone , and then use this function as a change handler for all of your elements.

+2
source

I think the second is better in this case. You can also use jQuery inside your function

http://jsperf.com/testaaa

jQuery call: 67,194 / sec

your function calls: 114,142,715 / sec

+1
source

All Articles