I have a list of products, where I need to update the innerHTML of a #container
dynamically.
My question is, if I do something like in this answer: Jquery Remove All Event Handlers Inside Element
$("#container").find("*").off();
So, I remove all the event handlers for all the children, and then I update the html:
$("#container").html(responseFromAJAX);
How will this affect on the performance? I mean, is this a good way, to remove all the old elements and handlers, and clean up memory, or I need to do more?
My app is a webshop, so my Users will look around, and update the #container
maybe 30-50 times/visit.
You can just use html(), like many of the other jQuery methods, it cleans up the event handlers and the associated data (which btw is not automatically cleaned up when elements are removed from the DOM).
$("#container").html(responseFromAJAX);
From the documentation :
When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Additionally, jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.
Event handlers, connected directly to DOM elements, die when the DOM elements are removed from the DOM.
Replacing the content is enough.
The rules for deferred events (event delegation) are different, as the events are not actually connected to the individual DOM elements, but are captured at a higher level (like the document
). A selector is then run and the event function run against the matching element(s). Deferred events tie up less memory but are a tiny(-tiny) bit slower to run (you will never notice the difference for mouse events) as the element search is only done when the event triggers.
I would generally recommend using deferred on
, instead of connecting to lots of individual elements, especially when your DOM elements are loaded dynamically.
e.g.
$(document).on('someeventname', 'somejQueryselector', function(e){
// Handle the event here
});
document
is the best default for several reasons if nothing else is closer/convenient). See notes for details.The upshot of this is that delegated handlers only match at event time, so can cope with dynamically added/removed content. The runtime overhead is actually lower at event registration (as it only connects to a single element) and the speed difference at event time is negligible (unless you can click a mouse 50,000 times per second!).
body
or document
if nothing else is handy.body
for delegated events can cause a bug to do with styling. This can mean mouse events do not bubble to body (if the computed height of body
is 0). document
is safer as it is not affected by styling.document
always exists, so you can attached delegated event handlers outside of a DOM-ready handler with no problems.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With