Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there any performance difference in between applying event using on or by direct event

Tags:

jquery

These days i am working on a jquery project and i found that if i use direct event like

$('.selector').click(function(){
});

will work perfect but in case of page partial post back or dynamic content i have to use .on as follow

$('body').on('click','.selector',function(){

});

Now my question is on work on static content as well on dynamic content , so why not i always use on directly instead of static event like click .

Is there any performance issue with .on

like image 957
rahularyansharma Avatar asked Jan 29 '26 05:01

rahularyansharma


1 Answers

Is there any performance issue with .on

There is no performance issue with .on. In fact, your first example is just a shortcut for:

$('.selector').on('click', function(){ 

The difference as you say is the use of $('body').on delegates the event for elements that are not yet in the DOM which naturally will require more work from the browser. If you need the delegation on the document or body then use that, otherwise use the other way.

like image 111
MrCode Avatar answered Jan 31 '26 18:01

MrCode