I am developing a web application and using quite a lot of JavaScript doing tasks. I have quite some tags that are bound with Jquery click to do some jobs, so I have code like this:
html code:
<a href="#" id="id1">some content here</a>
<a href="#" id="id2">some content here</a>
....
Jquery code:
$('#id1').click(function(){
//do something here..
return false;
});
$('#id2').click(function(){
//do something else here..
return false;
});
with this approach, when the script runs, jquery must look up the selectors (id1,id2, ect).
but there is another approach which avoid looking up selectors , this is as follow:
<a href="requireJs.htm" onclick="f1();return false">some content here</a>
<a href="requireJs.htm" onclick="f2();return false">some content here</a>
and js code:
function f1(){
//do something here..
});
function f2(){
//do something else here..
});
which approach is better, considering performance? thanks for help.
The real performance gain is by using only one event handler attached to the parent element, and catch the children element generated event with event.target, since events bubble up by default in JavaScript to the outermost parent.
Wrap your link in a div
Attach only one event listener to it
This is a big increase in speed, expecially in older browsers such as IE, and when you start to have really many events.
View example here