I’m dealing with some pages that are build using ajax calls to the server, so I am relying on .on() to attach event handlers to new items.
I was wondering, however, if, when possible, is it more efficient to rely on the old javascript:function() to call a function, whenever the event handler is a click.
Here’s an example.
I get from the server a link element a:
<a href="javascript:doMoreStuff()" class="classThatDoesMore">Do More!</a>
and I insert it in the document like so:
// ajax call and so
$(this).html(response);
To “do more” I then have two ways (there might be other ways but I’m not aware of them, but any suggestion is welcome!):
$(document).on("click",".clssThatDoesMore",function(){ // I need (document)
// here something will be done
});
or
doMoreStuff(){
// here something will be done as well
}
As far as I know both solutions are pretty much cross-browser (I’ve tested href="javascript:function()" and it goes back at least to IE8), but in case I’m wrong please let me know!
I was wondering if an excess of .on() “listeners” may pose to much load on the browser, and so if it is better to rely on javascript:function(), or if, on the contrary, .on() does not require much resources at all and having several .on() listeners in the page is not a problem.
PS I’ve abandoned onclick="doMoreStuff()" since in Safari it was not working, while in FF the same exact code was and so was in Safari if done usinge href="javascript:doMoreStuff().
PPS this is not the same old question js v. jquery, to me the point is not which in general terms is more efficient, I would like to understand what’s the best way in which this particular task can be achieved 🙂
javascript:doMoreStuff()is just as bad, if not worse, thanonclick="doMoreStuff()". You have a lack of flexibility, no fallback if JS is not enabled, and thejavascript:pseudo-protocol is not even compliant as I understand.Let’s forget about efficiency and just focus on the fact that
.onis much cleaner. You can separate it out from the html/ajax, and it’s very simple to see what you are doing and change it later.As for efficiency, I don’t think you will notice a difference.
.onis very slightly less efficient in that the click event has to traverse the DOM tree a bit to figure out whether the event should fire, but that’s very small potatoes.