使用JavaScript的事件委派而不是jQuery有性能上的好处吗? [英] Is there a performance benefit to using JavaScript's event delegation rather than jQuery's?

查看:44
本文介绍了使用JavaScript的事件委派而不是jQuery有性能上的好处吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript :

parent.addEventListener("click", function(e) {
  if (e.target === child) { code }
});

vs.

jQuery :

$(parent).on("click",child,function(){});

推荐答案

边际,jQuery的 on 方法做了更多的工作来为您提供额外的功能,例如在事件冒泡时运行选择器.根,因此事件来自您期望的元素;如果您不小心,可能会出现问题.引用事件效果"下的文档:

Marginal, jQuery's on method does a bit more work to give you extra functionality, like running a selector as the event bubbles up to the root, so the event comes from the element you're expecting; if you're not careful, that could be problematic. Citing the documentation, under Event Performance:

在文档树的顶部附近放置许多委派的事件处理程序可能会降低性能.每次事件发生时,jQuery必须将所有类型的所有附加事件的所有选择器与从事件目标到文档顶部的路径中的每个元素进行比较.

Attaching many delegated event handlers near the top of the document tree can degrade performance. Each time the event occurs, jQuery must compare all selectors of all attached events of that type to every element in the path from the event target up to the top of the document.

另一方面,普通的javascript做起来更简单,只会引发该元素下发生的任何事件,因此您必须非常具体.

Plain javascript on the other hand does something more straightforward, just raises any event that happened under that element, so you have to be very specific.

话虽如此,在正常情况下,例如几百个事件处理程序,对于现代引擎而言,性能差异可以忽略不计.

Having said that, the performance difference is negligible for modern engines under normal circumstances, like a few hundred event handlers.

但是,正如@Patrick指出的那样,在某些特殊情况下这可能是灾难性的,在某些特殊情况下,您需要跟踪和获取事件的数千个元素;在这种情况下,对于每个事件运行选择器都会降低性能.有时,您会受益于使用特殊的技术,例如仅将一个事件处理程序附加到所述元素的容器,并使用 e.target 来找出真正导致事件的原因.

However, as @Patrick points out, it could be disastrous for some special cases where you have thousands of elements you need to keep track of and get events from; running selectors in this case, for each event, will kill your performance. Sometimes you will benefit from using special techniques, like only attaching one event handler to the container of said elements and using e.target to find out what actually caused the event.

这篇关于使用JavaScript的事件委派而不是jQuery有性能上的好处吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆