使用JavaScript的事件委派而不是jQuery有性能上的好处吗?

编程入门 行业动态 更新时间:2024-10-28 10:29:18
本文介绍了使用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有性能上的好处吗?

本文发布于:2023-11-04 00:25:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556464.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:而不是   好处   性能   事件   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!