且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果将.on('click'事件)附加到$("body"),性能会受到影响吗?

更新时间:2023-02-06 11:09:25

除非您有数百个处理程序或非常大的文档,否则您不必担心性能.

You don't need to worry about performance, unless you have hundreds of handlers or extremely large document.

文档中提取:

在大多数情况下,诸如点击之类的事件很少发生,并且效果也不是重要问题.但是,诸如鼠标移动或滚动之类的高频事件每秒可能触发数十次,在这种情况下,明智地使用事件变得更加重要.可以通过减少处理程序本身中的工作量,缓存处理程序所需的信息(而不是重新计算信息)或通过使用setTimeout限制实际页面更新的速率来提高性能.

In most cases, an event such as click occurs infrequently and performance is not a significant concern. However, high frequency events such as mousemove or scroll can fire dozens of times per second, and in those cases it becomes more important to use events judiciously. Performance can be increased by reducing the amount of work done in the handler itself, caching information needed by the handler rather than recalculating it, or by rate-limiting the number of actual page updates using setTimeout.

在文档树顶部附近附加许多委派的事件处理程序会降低性能.每次事件发生时,jQuery必须将该类型所有附加事件的所有选择器与从事件目标到文档顶部的路径中的每个元素进行比较.为了获得***性能,请在尽可能靠近目标元素的文档位置附加委托事件.避免在大型文档上的委派事件中过度使用document或document.body.

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. For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of document or document.body for delegated events on large documents.