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 listene开发者_StackOverflow中文版rs 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
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.
精彩评论