使用事件侦听器添加多个元素的最快方法?监听窗口点击是否不好?
在我上一个问题之后,我提出了这个问题,这可能会更好。
我需要在页面上添加很多项目,我发现有时appendChild + fregment比innerHTML更快。无论如何,现在我需要知道添加元素和添加事件侦听器的最快方法。
我看到的一种方法是监听窗口对象然后进行过滤。 优点:
- 只添加一次,然后永远不会,
- 如果您忘记在删除事件侦听器之前删除事件侦听器,因为事件被添加到
- 其他窗口对象上,则不会出现内存陷阱?
缺点:
- 可能会慢一些?
- 速度较慢,因为我们需要过滤项目,并且每次都会监听所有内容......在这一点上可能太慢了,我不知道。
我知道的另一种方法是监听创建的元素。
但对于innerHTML,我认为仅适用于窗口对象侦听器。
还有其他意见吗? 谢谢
After my previous question I heve this one, that might be better.
I need to add a lot of items on the page and I see that sometimes appendChild+fregment is faster than innerHTML. Anyway now I would need to know the fastest way to add elements and add event listeners too.
One way I see is to listen on the window object and then filter.
Pros:
- Only add once, then never
- No memory trap if you forget to remove events listeners before remove as the event is added on the window object
- others?
Cons:
- Maybe slower?
- Slower as we need to filter the items and will listen for everything everyime... maybe too slow at this point, I don't know.
The other way I know is to listen on the created element.
But with innerHTML I think only works with the window object listener.
Any other oppinions?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
处理“许多”元素的“多个”事件处理程序的最佳实践是事件委托,这基本上就是您所描述的。
在最近的共享父节点上创建一个侦听器(
document.body
当然会为任何元素执行此操作,但下面可能还有另一个父节点)。性能不应该成为问题。创建大约 200 个事件处理函数而不是一个要糟糕得多。
Best practice to handle "multiple" event handlers for "many" elements is event delegation, which is basically what you described.
Create a listener on the closest shared parent (
document.body
will of course do it for any element, but maybe there is another parent node below that).Performance should not be the issue there. It's far worse to create like 200 event handler functions instead of one.