Есть проблемы с производительностью подписки на всплытие событий через jQuery. IE9 и IE11 указывают, что при клике 80% времени тратится на выполнение querySelectorAll
. Анализ привёл в функцию $.event.dispatch
(jQuery 1.8.1, в более новой версии (1.11.3) эта функциональность вынесена в $.event.handlers
), которая содержит такой код:
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
// Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
selMatch = {};
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = jQuery( sel, this ).index( cur ) >= 0;
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
}
}
}
Обращаю внимание на следующие строки:
// Для каждого элемента от кликнутого наверх
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
// Обнуляем кэш результатов поиска
selMatch = {};
// Для каждого из подписчиков
for ( i = 0; i < delegateCount; i++ ) {
// Берем селектор очередного подписчика
sel = handleObj.selector;
// Если такого селектора нет в кеше
if ( selMatch[ sel ] === undefined ) {
// Выполняем поиск всего соответствующего селектору
// И запоминаем, есть ли просматриваемый внешним циклом элемент среди найденного
selMatch[ sel ] = jQuery( sel, this ).index( cur ) >= 0;
Поскольку подписка сделана на всплытие до body
, каждый такой поиск вытаскивает из всего документа все элементы, соответствующие селектору. Причём, этот одинаковый список запрашивается столько раз, сколько родительских элементов имеет кликнутый.
Насколько я понимаю, внешний цикл нужен для правильной последовательности вызова обработчиков в порядке всплытия события. Есть кэш, который работает в пределах одного уровня вложенности и помогает только в случае многократной подписки на один и тот же селектор.
Собственно вопрос: почему кэш реализован именно так? Почему бы не сохранять в кэше найденный набор, а в последующий if перенести проверку вместе с index
?
Но это не всё. Я посмотрел реализацию в актуальной версии 1.11.3. В ней по-прежнему делается такое же количество запросов, но строка изменяется.
Вот что было в 1.8.1:
selMatch[ sel ] = jQuery( sel, this ).index( cur ) >= 0;
и вот что стало в 1.11.3:
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
Здесь уже такая модификация кэширования кажется сомнительной.
Итак, вопросы:
- По какой причине код мог быть написан именно таким неоптимальным способом.
- Как лучше поступить, чтобы избежать проблем с производительностью?
Следующий сниппет показывает проблему множественных вызовов поиска:
Надо открыть консоль браузера и нажать на Click me to get a lot of searches!
.
В консоль будет 21 раз выведено
qsa [id='sizcache041783330822363496'] section .smth
gbc smth-other
По поводу куска [id='sizcache041783330822363496']
есть родственный вопрос - эта форма убирает необходимость экранирования. Недавно в Sizzle было внесено изменение по этому поводу, но даже актуальная версия jQuery его не содержит.
$(function () {
$("body")
.on("click", "section .smth", function () { console.log("clicked", "section .smth") })
.on("click", ".smth-other", function () { console.log("clicked", ".smth-other") });
$("h1").text("Click me to get a lot of searches!");
var qsa = Element.prototype.querySelectorAll, gbc = Element.prototype.getElementsByClassName;
Element.prototype.querySelectorAll = function(s) { console.log('qsa', s); return qsa.apply(this, arguments) };
Element.prototype.getElementsByClassName = function(s) { console.log('gbc', s); return gbc.apply(this, arguments) };
});
body { counter-reset: lev 1; }
div { counter-increment: lev; }
h1, h2 { cursor: pointer; }
h1:hover, h2:hover { background: silver; }
h1:after { content: " (" counter(lev) ")"; }
<div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><div><h1>
Loading...
</h1></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div></div>
<section>
<h2 class="smth">I'm smth and i'm waiting for a click</h2>
</section>
<section>
<h2 class="smth-other">I'm smth other and i'm waiting for a click</h2>
</section>
<script src="//code.jquery.com/jquery-1.8.1.js"></script>
В следующий сниппет помещён код функции dispatch из jQuery 1.8.1 (сниппет нужен для получения сворачиваемого спойлера, пытаться его запускать бесполезно):
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event || window.event );
var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related,
handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = [].slice.call( arguments ),
run_all = !event.exclusive && !event.namespace,
special = jQuery.event.special[ event.type ] || {},
handlerQueue = [];
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers that should run if there are delegated events
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && !(event.button && event.type === "click") ) {
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
// Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
selMatch = {};
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = jQuery( sel, this ).index( cur ) >= 0;
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( handlers.length > delegateCount ) {
handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
}
// Run delegates first; they may want to stop propagation beneath us
for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
matched = handlerQueue[ i ];
event.currentTarget = matched.elem;
for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
handleObj = matched.matches[ j ];
// Triggered event must either 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
event.data = handleObj.data;
event.handleObj = handleObj;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},