0

my webapp is very slow and i start to investigate to find the reason. i think i find the problem, but not the solution. i analyzed with the console and you can see the result on the screen. the problem is everytime i click, there is a latency of almost 1000ms due to the event on the click. first, i think that was because of too many event click on the body in my code, but as you can see it's only between 0.3 and 1% if the total cost), very tiny compare to the 97.71% of n.event.handler. so my question is where this latency come from?

in my code, there is a lot of :

 $('html').on('click', '.class', function(){ });

maybe too much?

enter image description here

enter image description here

user3415011
  • 195
  • 1
  • 2
  • 11
  • 4
    How can we possibly answer this without seeing the code being run in that click handler? – Rory McCrossan Nov 20 '14 at 07:39
  • Try it with `$(document).on('click', '.class', function() {})`. It may not solve your problem, [but it's seemingly faster](http://jsperf.com/clickclclcl). – dan-lee Nov 20 '14 at 08:14
  • @DanLee you're testing the attachment of event handlers, not the calling. – lordvlad Nov 20 '14 at 08:24
  • how many of those do you have in your code? 10s? 100s? 1000s? – lordvlad Nov 20 '14 at 08:37
  • i think closest that 1000s than 100s – user3415011 Nov 20 '14 at 08:39
  • maybe you could try and use the unminified version of jquery, so that the function names make more sense? its hard to know what goes on in the functions `db` and `xb` which seem to be the culprits. – lordvlad Nov 20 '14 at 08:50
  • there is another question that might be of help: http://stackoverflow.com/questions/6576853/jquery-delegate-performance-on-the-click-event-on-large-lists-slows-down-if-yo?rq=1 – lordvlad Nov 20 '14 at 08:53

1 Answers1

1

If you think you have too many of these:

$('html').on('click', '.class', function(){ });

you could try and refactor them into one handler:

$('html').on('click', function (e) {

  if (e.target.classList.contains('class')) {
       // e.target is the clicked element
      // do something here
  }

  if ($(e.target).is('class2')) {
     // you can wrap e.target into a jQuery object
     // the same way you wrap this.
     // do something else here
  }

});

Also, according to an answer to this question, you should remove and add back those event handlers if you have lots of dynamically created targets.

Community
  • 1
  • 1
lordvlad
  • 5,200
  • 1
  • 24
  • 44
  • thank for this, but in that case how can i get the $('this') from the on click? – user3415011 Nov 24 '14 at 06:10
  • "this.classList.contains('class')", it's don't work, he can't find the class. with the e target that you wrote before it's working, but in my function i use the $(this), it's really usefull for me. – user3415011 Nov 25 '14 at 06:59
  • Aw cr*p, it was correct before. $(e.target) then equals the $(this) you'he been using before – lordvlad Nov 25 '14 at 10:33