admin管理员组

文章数量:1326146

Is it bad to not disconnect a MutationObserver?

I'm performing an observation for new elementes added to the DOM, but I'm never performing an explicit disconnection. Could this cause memory issues?

Is it bad to not disconnect a MutationObserver?

I'm performing an observation for new elementes added to the DOM, but I'm never performing an explicit disconnection. Could this cause memory issues?

Share Improve this question edited Dec 15, 2022 at 16:02 Ranjeet Eppakayala 3,0581 gold badge13 silver badges23 bronze badges asked Apr 17, 2015 at 13:22 Matías CánepaMatías Cánepa 5,9844 gold badges61 silver badges108 bronze badges 2
  • You mean, you need your MutationObserver to do stuff for the entire duration of the website being viewed? – Siguza Commented Apr 17, 2015 at 13:28
  • @Siguza at least while certain jQuery is open using this feature – Matías Cánepa Commented Apr 17, 2015 at 13:30
Add a ment  | 

1 Answer 1

Reset to default 8

If you need your MutationObserver only once (e.g. for initialization or whatever), you should disconnect it after it's no longer used. This might or might not free some memory, but it will certainly decrease CPU load.

If your MutationObserver is required for the normal functioning of your website and would only have to be disconnected when the user closes their tab or window, I would say disconnecting is not required, as the browser has to clean up anyway. I mean, you could unregister event handlers as well, but no-one really does that. And certainly no-one deletes all their functions and variables, they expect the browser to do that.
It might even be faster to not disconnect your MutationObserver, as the cleanup code is (almost certainly) written in machine code, which executes much faster than JavaScript. The difference would most likely be unnoticeable though.

And since you specifically ask

Could this cause memory issues?

Yes, it could create a memory leak. But so could declaring a variable, if the browser does not perform appropriate cleanup, which would be a bug in that browser.
Assuming a sane environment though, you should be fine without disconnecting your MO.

本文标签: javascriptIs it bad to not disconnect a MutationObserverStack Overflow