I'm trying to speed up the javascript execution in our app.
It looks like I've 900+ event listeners bound -
var listenerCount = 0;
var ael = Node.prototype.addEventListener;
Node.prototype.addEventListener = function() {
listenerCount++;
ael.apply(this, arguments);
}
And I understand that this will be effecting performance. Is it possible to speed things up by adjusting the way I register listeners? For example if I try and register on
events on the same element (with different selectors), will that be more efficient.
Eg changing
$('#sidebar').find('select').on('click', 'option', handler1);
$('#sidebar').find('.className').on('click', 'a', handler2);
for
$('#sidebar').on('click', 'select option', handler1);
$('#sidebar').on('click', '.className a', handler2);
Generally speaking I'm interested in the time it takes to register everything rather than the time it to actually run the handler (and I'm aware that different selectors perform differently). I'd probably swap an extra 10-50ms when the event is actually fired for 1-5ms reduction in registering the event - I want the app to load fast!
I was thinking of writing something that will do the selector matching so as to reduce the number of events actually registered, but I can't find anyone else doing anything similar (which makes me think it's probably dumb) -
var sideBarDomEvents = (function(){
var clickEvents = [],
my = {
init: function() {
$sidebar = $('#sidebar');
$sidebar.on('click', function(e){
for (var i=0; i < clickEvents.length; i++) {
if (clickEvents[i]['target'] == $(e.target) {
clickEvents[i]['handler'](e);
}
}
});
},
registerClickEvent: function($target, handler){
// This only works if the target is the inner most element - bubbling isn't supported!
clickEvents.push({'target':$target, 'handler': handler});
}
}
return my;
})();
I'm really not sure which way to go here - I don't even know where to measure this stuff (I certainly haven't noticed anything in Chrome's profile or timeline that relates). Any explanation of the performance effects of jquery events would be great.