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.
So, using a string that is tied to a function, onclick produces an attribute within the binded HTML tag. . click, on the other hand, attaches the function to the property element.
click is a function on HTML elements you can call to trigger their click handlers: element. click(); onclick is a property that reflects the onclick attribute and allows you to attach a "DOM0" handler to the element for when clicks occur: element.
Minimizing direct DOM manipulation improves jQuery performance. Every time an element is created and inserted, time and capacity is needed. Using a cached selector with the append() method reduces the need for capacity. The following example shows how applying DOM control improves performance.
jQuery bind() Method Use the on() method instead. The bind() method attaches one or more event handlers for selected elements, and specifies a function to run when the event occurs.
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
<div id="parent">
<a href="#" id="id1">some content here</a>
<a href="#" id="id2">some content here</a>
</div>
Attach only one event listener to it
$('#parent').click(function(event){
// event.target is now the element who originated the event
$(event.target).doSomething();
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With