问题描述
在单页应用程序中,通常会删除和替换元素.在从DOM中删除的元素上,可能有一个IntersectionObserver(或任何其他种类)
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)
对于事件,我从不打扰,因为它们是在目标上绑定并触发的,因此保留它们应该相当无害.对于IntersectionObserver,我有点担心所有实例是否在视图更改时都会得到检查.
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.
考虑我的Lazy.ts的以下部分
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
});
}
底部(mutationOberserver
)是否没用?由于document.body
的许多检查,它甚至可能会损害性能.
Is the bottom part (mutationOberserver
) useless or not? It might even harm performance because of the many checks on document.body
.
通常,我只是假设垃圾收集会很好地完成其工作,但是脚本保留了对所有Attached元素的引用数组.而且该数组不会被清除(并且没有观察者也无法清除)
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)
-编辑-
它不会被删除"(或至少在10秒内不会删除) https://jsfiddle.net/c1sgdcrd/因此,问题仍然存在,最好是将其保留在内存中或主动使用MutationObserver并断开连接.
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.
推荐答案
我还没有找到官方帖子,但是我将假定它与MutationObservers相同,即垃圾收集应该可以处理删除DOM元素后,即可删除.参见 https://dom.spec.whatwg.org/#garbage-collection
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
我还在这里发布了MO的答案:
I also posted the answer for MOs here: Should MutationObservers be removed/disconnected when the attached DOM node is removed like removeEventListener for events?
这篇关于删除元素时是否应断开IntersectionObserver的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!