Skip to content

Make it possible to observe connected-ness of a node #533

Open

Description

@rniwa

It would be useful to have a way of observing when a node gets connected or disconnected from a document similar to the way connectedCallback and disconnectedCallback work for custom elements but unlike those at the end of the microtask like all other mutation records.

Activity

  1. rniwa commented on Nov 4, 2017

    @rniwa
    Author
  2. domenic commented on Nov 4, 2017

    @domenic
    Member

    It wasn't clear from the original thread what the use cases were. @pemrouze just said it would be nice, then people started discussing how. We never even talked about why they couldn't use custom elements.

    I agree that if we had a need for this ability extending MutationObserver would be the way forward but I'd like some more justification in the form of concrete use cases that are hard to accomplish with custom elements.

  3. rniwa commented on Nov 4, 2017

    @rniwa
    Author

    Agreed. It's always good to have a list of concrete use cases before adding new API.

  4. smaug---- commented on Nov 4, 2017

    @smaug----
    Contributor

    IIRC this was discussed around the time when MutationObserver was designed and the idea was that since one can add childList observer to the document and then just check document.contains(node), that should in principle be enough (and the things to observe was kept in minimum).
    However Shadow DOM wasn't really a thing at that time, and that may have changed the needs.
    Concrete use cases, which can't be solved with Custom Elements, would be indeed nice.
    The more we add APIs, the more complicated platform we have to maintain and adding more and more API tends to slow down implementations, or at least makes it harder to optimize them.

  5. justinfagnani commented on Nov 4, 2017

    @justinfagnani

    This would be useful for polyfilling custom elements, but obviously that's not a good use case for why custom elements aren't enough.

    If I can page in my requests around MutationObservers one had to do with observing access shadow boundaries so we don't have to patch attachShadow, which might be relevant here, and have some way of unobserving nodes outside of disconnect(), say when the nodes are disconnected.

  6. pemrouz commented on Nov 4, 2017

    @pemrouz

    It wasn't clear from the original thread what the use cases were. @pemrouze just said it would be nice, then people started discussing how. We never even talked about why they couldn't use custom elements.

    • A framework that does some housekeeping when a component is removed (e.g. tearing down subscriptions). The framework is outside the component, so would have to rely on every component emitting this event manually which isn't feasible/reliable. The disconnectedCallback is the current solution, but it requires wrapping every component in a wrapper component. This has other benefits (e.g. dynamic registry), but the less that can be done at the framework level would be great and this seemed generic enough to enquire about.

    • It would be nice for a component to be able to declaratively manage subscriptions it's own subscriptions, rather than have to emit the event manually or be forced to imperatively manage the subscription (see original thread).

  7. smaug---- commented on Nov 5, 2017

    @smaug----
    Contributor

    Wouldn't a childList observer in document take care of those use cases, at least in common cases?

  8. pemrouz commented on Nov 5, 2017

    @pemrouz

    It's unfortunately notoriously difficult to do with MutationObserver, and pretty much guaranteed to be buggy (due to it being batched) and inefficient (having to watch every change on the entire document).

  9. WebReflection commented on Nov 8, 2017

    @WebReflection

    This would be useful for polyfilling custom elements

    polyfills for custom elements already work and are either based on MutationObserver or DOMNodeInserted/DOMNodeRemoved with a lookup for registered elements in the list of changed nodes.

    Using polyfills is a weak reason, specially because anythig new needs to be polyfilled too.

    However I do have a use case in hyperHTML too but I believe React and many other frameworks would love this feature as well.

    CustomElements mechanism to understand their life-cycle are excellent but not everyone writes Custom Elements based sites and knowing a generic form, input, list element, grid card, has been added/removed would be ace.

    in hyperHTML I do have control of each vanilla DOM component but I need to do this "dance" per each MutationObserver notification:

    function dispatchTarget(node, isConnected, type, e) {
        if (components.has(node)) {
          node.dispatchEvent(e || (e = new Event(type)));
        }
        // this is where it gets a bit ugly
        else {
          for (var
            nodes = node.children,
            i = 0, length = nodes.length;
            i < length; i++
          ) {
            e = dispatchTarget(nodes[i], isConnected, type, e);
          }
        }
        return e;
      }

    The dispatching after recursive search is done per each record.addedNodes and record.removedNodes but if I had a platform way to loop over all known connected/disconnected nodes my code, and my life, would definitively be easier.

  10. pemrouz commented on Dec 19, 2017

    @pemrouz

    @domenic any more thoughts?

  11. rniwa commented on Feb 17, 2018

    @rniwa
    Author

    Here's a concrete use case. A editor library wants to know when the editor lost the focus. Because blur event does not fire on an element that got disconnected from a document before losing the focus, we'd need to monitor when the element is disconnected. To do this, we currently need to monitor all child node changes of the parent node, and then detect when the editor node is removed. With the proposed observation type, we can observe the disconnection of the editor element instead.

  12. WebReflection commented on Feb 21, 2018

    @WebReflection
  13. smaug---- commented on Feb 21, 2018

    @smaug----
  14. rniwa commented on Feb 21, 2018

    @rniwa
    Author
  15. WebReflection commented on Feb 22, 2018

    @WebReflection
  16. 47 remaining items

  17. dead-claudia commented on Apr 30, 2025

    @dead-claudia

    @FrameMuse His connected ≈ my liveness. I noted that browsers in practice track it via a bit.

    And connection is a direct consequence of mutations, just not of the element itself. Consider that connection is when iframes and images start their initial load.

  18. FrameMuse commented on Apr 30, 2025

    @FrameMuse

    @dead-claudia

    And connection is a direct consequence of mutations

    just not of the element itself

    I guess this is what makes it indirect. This is what I was referring to - indirect mutation observing.

    Consider that connection is when iframes and images start their initial load.

    I don't think the connection events should fire when HTML is parsed, only when connections done to existing DOM in memory.

  19. dead-claudia commented on Apr 30, 2025

    @dead-claudia

    Consider that connection is when iframes and images start their initial load.

    I don't think the connection events should fire when HTML is parsed, only when connections done to existing DOM in memory.

    @FrameMuse I'm talking about script-created elements here. These are called on dynamic insertion as well as during initial HTML tree building. And here's the part for iframes I was referring to.

    I'm also expressly just asking for a way to observe that in-practice browser bit flag, so while in theory it's indirect, it in practice is very much direct observation of a node's mutable state.

  20. jamesdiacono commented on May 1, 2025

    @jamesdiacono

    Could Nodes simply emit non-bubbling "connect" and "disconnect" events? That would let us do everything that currently requires connectedCallback and disconnectedCallback.

  21. wessberg commented on May 1, 2025

    @wessberg

    @jamesdiacono

    We've been down that path before with MutationEvents which caused many issues and was later unshipped from browsers.

    Instead I think we may be able to achieve consensus that adding a connected (or similar wording) to MutationObserver is the way forward? Based on recent discussion in this thread it seems like the approach most favored. And I'm also leaning towards agreeing that its better than my original idea of a dedicated observer.

  22. FrameMuse commented on May 1, 2025

    @FrameMuse

    @dead-claudia Yeah, it depends how you think about it. So let's say we both understand each other. I'm just saying adding ~connected to MutationObserver is not immediately natural, but it'd be still very quick to adapt and get used to.

    @wessberg I don't really mind for now, we can think about better place after it's shipped to browsers and countless experiments.

  23. FrameMuse commented on May 1, 2025

    @FrameMuse

    @jamesdiacono AFAIK, Events have different scheduling comparing to MutationObserver and they have many more properties than MutationObserver, they might be useful, but as this topic is already associated with MutationObserver, which historically had a problematic version of MutationEvent - seems olds won't accept something related to go this path again.

  24. LeaVerou commented on Dec 12, 2025

    @LeaVerou
    Member

    Actually, I’m not sure if observing connectedness is what we need. Consider this:

    let parser = new DOMParser();
    let doc = (new DOMParser).parseFromString("<p>Hi</p>", "text/html");
    let p = doc.querySelector("p");
    console.log(p.isConnected); // true

    It seems that instead what most use cases need is to observe (a) ownerDocument changes and (b) parentNode changes.

    Then we can get all the existing custom element lifecycle hooks:

    • connectedCallback() → ownerDocument goes from null to a non-null value
    • disconnectedCallback() → ownerDocument changes from a non-null value to null
    • adoptedCallback() → ownerDocument changes from a non-null value to a different non-null value.
    • connectedMoveCallback() → parentNode changes from a non-null value to another non-null value, while ownerDocument remains the same

    Plus introducing such properties to MutationObserverInit is also much more in line with its existing API where options describe the lower-level tree variables. Connectedness is a derived variable.

  25. rniwa commented on Dec 12, 2025

    @rniwa
    Author

    It seems that instead what most use cases need is to observe (a) ownerDocument changes and (b) parentNode changes.

    Then we can get all the existing custom element lifecycle hooks:

    • connectedCallback() → ownerDocument goes from null to a non-null value
    • disconnectedCallback() → ownerDocument changes from a non-null value to null

    ownerDocument is never null so this won't work.

  26. LeaVerou commented on Dec 12, 2025

    @LeaVerou
    Member

    Ah, right, d'uh! 🤦🏽‍♀️
    Now I’m wondering if we need a property that does work like this… 😅
    Basically something like:

    get document () {
    	let root = this.getRootNode({ composed: true });
    	return root.nodeType === Node.DOCUMENT_TYPE ? root : null;
    }

    Whether such a DOM property exists or not, we could introduce a document option that works this way.
    Or, alternatively, a root option that lets you observe changes to either the composed root, the tree root, or both.
    That actually seems to be even more broadly useful than what I was proposing above.

    Observing ownerDocument still seems useful for implementing adoptedCallback, but clearly not for anything else.

  27. FrameMuse commented on Dec 12, 2025

    @FrameMuse

    @LeaVerou I think you misinterpret it, with DOMParser you create a brand new document, thus you have all the elements are "connected". isConnected is true only when it's connected to a document, so

    div = document.createElement("div")
    div.append(123)
    div.childNodes[0].isConnected // => false
    
    document.body.append(div)
    div.childNodes[0].isConnected // => true

    though ownerDocument will stay the same.

    So why we need connection (isConnected) observer? When an element is disconnected, we want any associated subscriptions to be unsubscribed and when it's connected - subscribe back. Another use-case is to enforce placement of an element as you can track where it's connected/disconnected from and add it back - this particular use-case can solve fundamental issues for "fragments".

  28. trusktr commented on Oct 5, 2026

    @trusktr

    Any chance we can add this? It seems like a nice quality of life improvement for something that is otherwise too cumbersome to implement, and simple for an engine to implement because it has access to all internals.

    We currently need hacky code in user space: to observe connectedness of only a single element, we'd need to patch attachShadow to make an MO for document and every root (like in #533 (comment)) which seems overcooked for user space code (and how do we even intercept closed declarative shadow roots?).

  29. added 2 commits that reference this issue on Oct 8, 2026
    7bdca97
    8c58089
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions