In a Single Page Application, elements are often removed and replaced. On elements that are removed from the DOM there could be an IntersectionObserver(or any other kind)
For events I never bothered to care because they are bound and triggered on the target so they should be rather harmless to keep. For the IntersectionObserver I'm somewhat worried all instances are checked on any view change.
Consider the following part of my Lazy.ts
setIntersectionObserver(config:LazyConfig)
{
let intersectionObserver = new IntersectionObserver((entries:Array<IntersectionObserverEntry>) => {
for (let entry of entries) {
if (entry.isIntersecting) {
this.lazyLoad(config);
intersectionObserver.disconnect();
mutationOberserver.disconnect();
}
}
}, {
threshold: 0,
rootMargin: `${config.offset}px`,
});
intersectionObserver.observe(config.element);
let mutationOberserver = new MutationObserver((entries:Array<MutationRecord>) => {
if (
entries[0].removedNodes &&
document.body.contains(config.element) === false
) {
intersectionObserver.disconnect();
mutationOberserver.disconnect();
}
});
mutationOberserver.observe(document.body, {
childList: true,
subtree: true
});
}
Is the bottom part (mutationOberserver
) useless or not? It might even harm performance because of the many checks on document.body
.
Usually I would just assume garbage collection will do its job just fine, but the script keeps an array of references to all Attached elements. And that array does not get cleaned (and can't be cleaned without the Observers)
--Edit--
It does not get "deleted" (or at least not in 10 seconds) https://jsfiddle.net/c1sgdcrd/ So, the question still stands wether it's better to just keep it in memory or actively use the MutationObserver and disconnect it.
I can't find an official post yet, but I'm going to assume it's the same as MutationObservers, which is that garbage collection is supposed to handle the removing once the DOM element is removed. See https://dom.spec.whatwg.org/#garbage-collection
I also posted the answer for MOs here: Should MutationObservers be removed/disconnected when the attached DOM node is removed like removeEventListener for events?
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