You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Make it possible to observe connected-ness of a node #533
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.
Reacted by Andrea Giammarchi, Tomek Wytrębowicz, James Browning, Frederik Wessberg, Caridy Patiño, Andreas Mehlsen, Andy Earnshaw, Joe Pea, Karl Horky, Joshua Peek and 46 more
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.
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.
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.
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).
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).
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:
functiondispatchTarget(node,isConnected,type,e){if(components.has(node)){node.dispatchEvent(e||(e=newEvent(type)));}// this is where it gets a bit uglyelse{for(varnodes=node.children,i=0,length=nodes.length;i<length;i++){e=dispatchTarget(nodes[i],isConnected,type,e);}}returne;}
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.
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.
Reacted by Pedram Emrouznejad, tomtheisen, Jonathan Neal, Arad Alvand, Tito and Bruce B. Anderson
@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.
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.
Could Nodes simply emit non-bubbling "connect" and "disconnect" events? That would let us do everything that currently requires connectedCallback and disconnectedCallback.
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.
Reacted by Valery Zinchenko, Claudia Meadows and Mike Matuszak
@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.
@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.
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.
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.
@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
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".
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?).
Activity
rniwa commentedon Nov 4, 2017
@smaug---- @justinfagnani
domenic commentedon Nov 4, 2017
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.
rniwa commentedon Nov 4, 2017
Agreed. It's always good to have a list of concrete use cases before adding new API.
smaug---- commentedon Nov 4, 2017
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.
justinfagnani commentedon Nov 4, 2017
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.
pemrouz commentedon Nov 4, 2017
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
disconnectedCallbackis 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).
smaug---- commentedon Nov 5, 2017
Wouldn't a childList observer in document take care of those use cases, at least in common cases?
pemrouz commentedon Nov 5, 2017
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).
WebReflection commentedon Nov 8, 2017
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:
The dispatching after recursive search is done per each
record.addedNodesandrecord.removedNodesbut if I had a platform way to loop over all known connected/disconnected nodes my code, and my life, would definitively be easier.pemrouz commentedon Dec 19, 2017
@domenic any more thoughts?
rniwa commentedon Feb 17, 2018
Here's a concrete use case. A editor library wants to know when the editor lost the focus. Because
blurevent 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.WebReflection commentedon Feb 21, 2018
smaug---- commentedon Feb 21, 2018
rniwa commentedon Feb 21, 2018
WebReflection commentedon Feb 22, 2018
47 remaining items
dead-claudia commentedon Apr 30, 2025
@FrameMuse His
connected≈ myliveness. 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.
FrameMuse commentedon Apr 30, 2025
@dead-claudia
I guess this is what makes it indirect. This is what I was referring to - indirect mutation observing.
I don't think the connection events should fire when HTML is parsed, only when connections done to existing DOM in memory.
dead-claudia commentedon Apr 30, 2025
@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.
jamesdiacono commentedon May 1, 2025
Could Nodes simply emit non-bubbling "connect" and "disconnect" events? That would let us do everything that currently requires
connectedCallbackanddisconnectedCallback.wessberg commentedon May 1, 2025
@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) toMutationObserveris 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.FrameMuse commentedon May 1, 2025
@dead-claudia Yeah, it depends how you think about it. So let's say we both understand each other. I'm just saying adding ~
connectedtoMutationObserveris 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.
FrameMuse commentedon May 1, 2025
@jamesdiacono AFAIK,
Events have different scheduling comparing toMutationObserverand they have many more properties thanMutationObserver, they might be useful, but as this topic is already associated withMutationObserver, which historically had a problematic version ofMutationEvent- seems olds won't accept something related to go this path again.LeaVerou commentedon Dec 12, 2025
Actually, I’m not sure if observing connectedness is what we need. Consider this:
It seems that instead what most use cases need is to observe (a)
ownerDocumentchanges and (b)parentNodechanges.Then we can get all the existing custom element lifecycle hooks:
connectedCallback()→ownerDocumentgoes fromnullto a non-null valuedisconnectedCallback()→ownerDocumentchanges from a non-null value tonulladoptedCallback()→ownerDocumentchanges from a non-null value to a different non-null value.connectedMoveCallback()→parentNodechanges from a non-null value to another non-null value, whileownerDocumentremains the samePlus introducing such properties to
MutationObserverInitis also much more in line with its existing API where options describe the lower-level tree variables. Connectedness is a derived variable.rniwa commentedon Dec 12, 2025
ownerDocumentis nevernullso this won't work.LeaVerou commentedon Dec 12, 2025
Ah, right, d'uh! 🤦🏽♀️
Now I’m wondering if we need a property that does work like this… 😅
Basically something like:
Whether such a DOM property exists or not, we could introduce a
documentoption that works this way.Or, alternatively, a
rootoption 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
ownerDocumentstill seems useful for implementingadoptedCallback, but clearly not for anything else.FrameMuse commentedon Dec 12, 2025
@LeaVerou I think you misinterpret it, with
DOMParseryou create a brand new document, thus you have all the elements are "connected".isConnectedis true only when it's connected to a document, sothough
ownerDocumentwill 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".trusktr commentedon Oct 5, 2026
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
attachShadowto make an MO fordocumentand every root (like in #533 (comment)) which seems overcooked for user space code (and how do we even intercept closed declarative shadow roots?).Allow MutationObserver to observe connectedness and add unobserve()
Allow MutationObserver to observe connectedness and add unobserve()