Does Performance Suffer If I Attach .on('click' Events To $("body")?
Solution 1:
You don't need to worry about performance, unless you have hundreds of handlers or extremely large document.
Extract from documentation:
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.
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.
Solution 2:
In jQuery, the higher up you place the .on() in the DOM, the slower it will be. This is because jQuery must compare all selectors of all attached events of the selected type from the target to the document level.
See the jQuery documentation page for .on():
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.
With this being said, the performance difference may likely be negligible for click events since, unlike scrolling or mouse movement events, they fire infrequently (only on the user's click).
Post a Comment for "Does Performance Suffer If I Attach .on('click' Events To $("body")?"