gpt4 book ai didi

javascript - 删除元素时是否应断开 IntersectionObserver

转载 作者:搜寻专家 更新时间:2023-11-01 04:35:02 27 4
gpt4 key购买 nike

在单页应用程序中,元素经常被删除和替换。在从 DOM 中移除的元素上可能有一个 IntersectionObserver(或任何其他类型)

对于我从不关心的事件,因为它们是在目标上绑定(bind)和触发的,所以保留它们应该是无害的。对于 IntersectionObserver,我有点担心在任何 View 更改时都会检查所有实例。

考虑我的 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 进行了许多检查,它甚至可能会损害性能。

通常我只是假设垃圾回收会很好地完成它的工作,但脚本保留了一个对所有附加元素的引用数组。并且该数组不会被清理(没有观察者就无法清理)

--编辑--

它不会被“删除”(或者至少在 10 秒内不会)https://jsfiddle.net/c1sgdcrd/因此,问题仍然存在,是将其保存在内存中还是主动使用 MutationObserver 并断开连接更好。

最佳答案

我还找不到官方帖子,但我假设它与 MutationObservers 相同,即一旦 DOM 元素被移除,垃圾回收应该处理移除。参见 https://dom.spec.whatwg.org/#garbage-collection

我还在此处发布了 MO 的答案:Should MutationObservers be removed/disconnected when the attached DOM node is removed like removeEventListener for events?

关于javascript - 删除元素时是否应断开 IntersectionObserver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47942804/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com