简体   繁体   English

有什么更好的性能:立即设置所有dom事件还是逐步设置?

[英]What is the better for performance: set all dom events at once, or progressively?

Is it better to add events listeners once and for all? 一劳永逸地添加事件侦听器是否更好? Or just before an event is likely to happen? 还是在事件可能发生之前?

An example: imagine you have a menu in your HTML, which opens on click. 例如:假设您的HTML中有一个菜单,单击该菜单即可打开。 You have also a close button in this menu, which closes the menu on click. 您在此菜单中还有一个关闭按钮,单击后会关闭菜单。 The event listener on the close button should be set: at page load or only when the menu opens? 应该设置关闭按钮上的事件侦听器:是在页面加载时还是仅在菜单打开时?

In other words, is this: 换句话说,是这样的:

function open() {
  closeButton.addEventListener('click', close);
  // ...
}
function close() {
  closeButton.removeEventListener('click', close);
  // ...
}
openButton.addEventListener('click', open);

better/faster than just this? 比这更好/更快?

function open() {
  // ...
}
function close() {
  // ...
}
openButton.addEventListener('click', open);
closeButton.addEventListener('click', close);

I always prefer to choose simplicity over performance, but does it make a difference at all? 我总是更喜欢简单而不是性能,但这有什么不同吗? Especially when there are lots of events in the UI? 特别是在UI中有很多事件时?

When we know that a event is unlikely to happen untile a certain dependent event, we should defer the event binding. 当我们知道某个事件直到某个相关事件才不太可能发生时,我们应该推迟事件绑定。 That way the DOM is less heavy 这样,DOM就不那么繁重了

As for the simplicity part, we can have simplified version of code even for he deferred binding of events 至于简单性部分,即使他推迟了事件绑定,我们也可以简化代码版本

Thank you all for your opinion on that matter! 谢谢大家对此事的意见!

I'm settling to this: bind directly for click and other obvious actions, and bind later for keyboard and mouse events. 我要解决这个问题:直接为单击和其他明显的动作绑定,然后为键盘和鼠标事件绑定。

In the example, if we want to close the menu when the user press Escape, then we add the event listener on the keydown event to test e.key === "Escape" only when the menu is open. 在此示例中,如果我们要在用户按下Escape键时关闭菜单,则仅在打开菜单时才在keydown事件上添加事件侦听器以测试e.key === "Escape" And we remove that listener when the menu is closed. 当菜单关闭时,我们将删除该侦听器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM