Should an IntersectionObserver be disconnected when element is removed

喜夏-厌秋 提交于 2019-12-10 14:51:17

问题


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.


回答1:


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?



来源:https://stackoverflow.com/questions/47942804/should-an-intersectionobserver-be-disconnected-when-element-is-removed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!