Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/446.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 删除元素时是否应断开IntersectionObserver的连接_Javascript_Performance_Dom_Mutation Observers_Intersection Observer - Fatal编程技术网

Javascript 删除元素时是否应断开IntersectionObserver的连接

Javascript 删除元素时是否应断开IntersectionObserver的连接,javascript,performance,dom,mutation-observers,intersection-observer,Javascript,Performance,Dom,Mutation Observers,Intersection Observer,在单页应用程序中,元素经常被删除和替换。在从DOM中删除的元素上,可能存在IntersectionObserver(或任何其他类型) 对于我从不在意的事件,因为它们是在目标上绑定和触发的,所以它们应该是无害的。对于IntersectionObserver,我有点担心任何视图更改都会检查所有实例 考虑我的Lazy.ts的以下部分 setIntersectionObserver(配置:LazyConfig) { 让intersectionObserver=新的intersectionObserver

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

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

考虑我的Lazy.ts的以下部分

setIntersectionObserver(配置:LazyConfig)
{
让intersectionObserver=新的intersectionObserver((条目:数组)=>{
for(让条目的输入){
if(输入。isIntersecting){
这个.lazyLoad(config);
intersectionObserver.disconnect();
mutationOberserver.disconnect();
}
}
}, {
阈值:0,
rootMargin:`${config.offset}px`,
});
intersectionObserver.observe(config.element);
让mutationOberserver=新的MutationObserver((条目:数组)=>{
如果(
条目[0]。removedNodes&&
document.body.contains(config.element)==false
) {
intersectionObserver.disconnect();
mutationOberserver.disconnect();
}
});
MutationOrberServer.observe(document.body{
儿童名单:是的,
子树:真
});
}
底部部分(
mutationorserver
)是否无用?由于对
document.body
进行了多次检查,这甚至可能会损害性能

通常我会假设垃圾收集可以很好地完成它的工作,但是脚本保留了对所有附加元素的引用数组。而且该阵列不会被清理(并且在没有观察者的情况下无法清理)

--编辑--


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

我还找不到官方帖子,但我假设它与MutationObserver相同,也就是说,一旦删除DOM元素,垃圾收集就应该处理删除操作。看


我还在这里发布了MOs的答案:

@wOxxOm我不确定是否“删除”,因为我保留了引用。它只是从文档中删除,而不是永久删除。但是我想IntersectionObserver也一样吗?我认为
删除
意味着垃圾收集,而不是
分离
,所以在您的情况下是否定的。无论如何,规范和API本身都处于PoC级别,因此您可能需要与规范作者澄清这一方面。是否可以将脚本更改为使用元素的弱映射,而不是数组?然后可以对元素进行垃圾收集,IntersectionObserver将在收集元素时停止观察它们。当我删除正在观察的元素并在其位置添加新元素时,我发现了一些奇怪的错误。我的回调将启动,我将在条目列表中看到旧目标,但它们没有父节点或位置信息。一旦我在删除这些元素之前
unobserved()
这些元素,问题就消失了。