Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

never disconnect a MutationObserver

Tags:

javascript

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?

like image 781
Matías Cánepa Avatar asked Apr 17 '15 13:04

Matías Cánepa


People also ask

How to disconnect MutationObserver?

disconnect() The MutationObserver method disconnect() tells the observer to stop watching for mutations. The observer can be reused by calling its observe() method again.

Do you need to disconnect mutation observer?

Disconnecting the observer tells it to stop watching for changes and is generally a best practice if you don't need to continually watch the element for changes. Here, we're also only targeting the first mutation with mutations[0] .

Is MutationObserver slow?

Good answer! Yes, it's finally slower by just 10% or even less in recent versions of Chrome. @Bergi, it's for the case when processing is complex and takes a lot of time. MutationObserver runs in a microtask queue so multiple callbacks may still reside in one task, which can lead to very long paint frames and jank.

What is MutationObserver in Javascript?

The MutationObserver interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature, which was part of the DOM3 Events specification.


1 Answers

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.

like image 191
Siguza Avatar answered Oct 10 '22 23:10

Siguza