javascript - Attaching events after Ajax load vs delegate events: what factors to consider? -


please consider scenario: load html page using ajax bunch of buttons. need attach events these buttons after load.

what factors should developer consider when choosing between delegating events on container or attaching events after load?

i asking because never know method use. attach events after load because can use data ajax response. performance-wise method better? there well-known pros , cons each approach's performance?

examples:

attaching events after load

var $cont = $(".container");  $.get("test.html", function(data) {   $cont.html(data);        initevents(); // use because can use/pass data response });  var initevents = function() {     $cont.find('.my-button').click(function() {         // ... magic ...     });     $cont.find('.my-other-button').click(function() {         // ... magic ...     }); } 

delegating events

var $cont = $(".container");     $.get("test.html", function(data) {   $cont.html(data); });  $cont.on("click", ".my-button", function() {   // ... magic ... });  $cont.on("click", ".my-other-button", function() {   // ... magic ... }); 

the issue not black or white.

to extent, it's down preference , opinion. favour delegating events means that, when content loaded - and, crucially, re-loaded later, perhaps, result of filters - events stuff active. clean.

delegation usually means lighter workload browser. rather attach 100 events, 1 logged, , event target evaluated when event fires.

furthermore, delegation can avoid duplicated running of code. had:

$.get('some_script.php').done(function() {     $('.foo').on('click', function() { ... }); }); 

you're registering event each , every time content loaded, whereas delegation means have run once.

when not delegate? well, if event-binding code substantial or weighty, such may wish defer execution, there argument until content has loaded. way stagger load weight of page.

in short, in exceptional cases, suggest delegation.


Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -