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
Need a callback for when children changed or parser finished parsing children #809
There appears to be a strong desire for having some callback when the parser finishes parsing children or when a new child is inserted or an old child is removed.
Previously, children changed callback was deemed too expensive but I'm not certain that would necessarily be the case given all major browser engines (Blink, Gecko, and WebKit) have builtin mechanism to listen to children changes.
I think we should consider adding this callback once for all. As much as I'd like to make sure custom elements people write are good, developer ergonomics here is quite terrible, and people are resorting to very awkward workarounds like attaching mutation observers everywhere, which is arguably far slower.
Reacted by Frank Topel, Andrea Giammarchi, James Browning, Pierre-Marie Dartus, Bruce B. Anderson, xlaywan, Justin Fagnani, Caridy Patiño, Tomek Wytrębowicz, Theo and 54 more
Not sure if this is possible but would it be possible to simply capture the value of childrenChangedCallback immediately after the element is constructed? Then one could easily enable an optimization that doesn't bother watching the children at all if the callback isn't actually provided.
(This would be similar to the iterator.next changes in for-of loops that .next is only captured once at the start of the loop).
EDIT: It looks like the other methods already work like this by capturing the methods off the prototype (TIL).
I support adding a children changed callback as that is indeed a primitive the DOM Standard provides and specifications and implementations use. (Firefox also has internal synchronous mutation observers, but nothing in the platform relies on them, though Firefox does currently use them for the output element.)
Before we add this however I'd like whatwg/dom#732 (review) solved. In particular, the primitive I referenced above isn't defined that well and some refactoring is needed. It'd be good to settle on the exact shape in private first before exposing it publicly.
As with #550, I do not support this if it is parser-specific. If it is just a CEReactions-time MutationObserver that only custom elements can install, then I'm open to investigating. In that case I think we should also seriously consider un-deprecating DOMNodeRemoved/DOMNodeInserted as an API shape, since that already exists in some browsers and we've needed to spec it properly for some time.
If it is just a CEReactions-time MutationObserver that only custom elements can install
I would love it to be a bit more than that, in that it observes projected children as well. I know that's covered slotchange, but currently you need to combine slotchange and a MO to implement "effective children changed".
A common ask that keeps coming up is the ability to know when a child node has been inserted & updated: e.g. #765, #619, #615
To do this, just knowing when a child is inserted or removed isn't quite enough due to async / out-of-order upgrading. Perhaps we need both childChangedCallback and childDefinedCallback the latter of which gets called when a child node is inserted & upgraded / defined.
@rniwa do you foresee this as something that can be observed in a custom element or a more low level API that can be applied to any element? It is not clear from the title or description.
@rniwa do you foresee this as something that can be observed in a custom element or a more low level API that can be applied to any element? It is not clear from the title or description.
I think this needs to be a custom element reaction callback.
I think this needs to be a custom element reaction callback.
That's probably limiting. I feel that this is in the same boat as the connect/disconnect reaction that we were asking for last week during the F2F, something a lot more generic.
Now, if we were to add a new reaction callback, will that callback be invoked even when the CE is not connected to the DOM? e.g.:
I think this needs to be a custom element reaction callback.
That's probably limiting. I feel that this is in the same boat as the connect/disconnect reaction that we were asking for last week during the F2F, something a lot more generic.
For general nodes, you can just use MutationObserver. If you wanted it sooner, then that's a discussion that has to happen in whatwg/dom#533
Now, if we were to add a new reaction callback, will that callback be invoked even when the CE is not connected to the DOM?
You mean when it's not connected to a document? If so, then yes. There is no reason to restrict this childChangedCallback to the connected nodes.
To me it seems to reliably access children in connectedCallback, one has to check for both existing children (which is the case when the element is appended to the DOM via .innerHTML or similar methods like Vue does it), and for regular DOM content where the children will be available after a childList mutation. Related demos.
Just to clarify @silverwind it looks like your code is only for change events, and even then, only on the first change and doesn't cover the use case of indicating when the parser has completed parsing and appending children of a particular element on the DOM.
The use case (one of them, at least) is waiting for <script> tags to finish parsing (and therefore contain all of the script) and then moving the script element between documents. If there's no way to know when all of the script is there, it's brittle.
I'm not sure we have a list of the use cases the web is "designed for". We provide functionality, and creative developers build cool things with that functionality. Parsing <script>s and moving them between documents is certainly one part of that functionality that seems like fair game.
Another use case (for builtin elements) is source selection for <video>. The conclusion on that issue seems to be that the best behavior is indeed to wait for the end tag before making a source selection. If that conclusion sticks, it'll be another instance of something a built-in element can do that a custom element cannot, because of the lack of the API this issue proposes.
To me it seems to reliably access children in connectedCallback, one has to check for both existing children (which is the case when the element is appended to the DOM via .innerHTML or similar methods like Vue does it), and for regular DOM content where the children will be available after a childList mutation. Related demos.
Honstly, it seems way to much boilerplate for such a simple and common use case.
Say a component has many children, is there any chance the parser may connect the component after parsing some of the children, i.e. not all of them. It appears to this code assumes that all the children exist, or none of them at the time the connectedCallback runs. (I am not sure if this is the case?).
Say a component has many children, is there any chance the parser may connect the component after parsing some of the children
if you define your component at the end of the page you are 100% sure you can access its children and everything else as it gets just "promoted" as CE ... if you define your component AOT (which is 90% of what libraries do instead of lazy dafining their components only when needed/encountered) you are 100% sure (last time I've checked) the connectedCallback will trigger instantly after attributeChangedCallback in case it was defined and the attribute is observed and encountered ... at that point the browser hasn't parsed yet the content of that element so you'll fallback with MutationObserver for children which guarantees nothing but usually it works "good enough".
The whole issue is to have something that never fails and that can be used in all circumstances and definition time, something that while streaming a document will signal via closedCallback that its ending has been encountered, something that even with lazy / late definitions will still trigger after the connectedCallback.
The problem raised in here is that in some streaming scenario the browser might already consider the element closed ... add people with "smart suggestions" like "don't need to close a<p>or a<li>" 'cause the browser does that for you, see early hacks on never closing a <body> because the browser does that for you (and the legend say it's faster in doing so) and so on ... so the issue remains and solutions are all awkward in a way or another, or really not applied via lazy custom elements definition, something I've explored ages ago, something that works and never suffers the issue itself but developers don't like it for other reasons (FOUC or other related shenanigans that might be indeed a concern specially with 100% ShadowDOM based components).
if you define your component at the end of the page you are 100% sure you can access its children and everything else as it gets just "promoted" as CE ... if you define your component AOT (which is 90% of what libraries do instead of lazy dafining their components only when needed/encountered) you are 100% sure (last time I've checked) the connectedCallback will trigger instantly after attributeChangedCallback in case it was defined and the attribute is observed and encountered ... at that point the browser hasn't parsed yet the content of that element so you'll fallback with MutationObserver for children which guarantees nothing but usually it works "good enough".
Often you have components that need to be loaded quickly, e.g. if they are above the fold. Putting them last on the page does not work in this case. It's kind of like putting your stylesheets just your closing </body>.
For now I make a function that handles slotted children, that function has to be idempotent.
When the component is connected:
I setup a eventHandler for slotchange, that calls this function, this.addEventListener('slotchange', this.slotChangeHandler.bind(this))
Set a zero wait timeout to call this function almost immediately, e.g. setTimeout(this.slotChangeHandler.bind(this))
This handles the situation when the children are added before the component can initialise, and when they are slotted after it has been initialised. A bit clunky but don't know of any better.
Updating on my case of streaming into a detached document and selectively moving nodes to the visible document. I found a much more efficient solution that also reliably identifies the closing tag by skipping the MutationObserver altogether and using a NodeIterator instead. Something similar might be possible for other use cases. Rough solution:
// Only works when streaming into an empty detached document. Otherwise additional logic is needed.functionelementIsClosed(element){letcurrentElement=element;while(currentElement){if(currentElement.nextSibling)returntrue;currentElement=currentElement.parentElement;}returnfalse;}constiterator=newNodeIterator(detachedDocument,NodeFilter.SHOW_ELEMENT);letelement;constresponse=awaitfetch("https://example.com");constreader=response.body.pipeThrough(newTextDecoderStream()).getReader();while(true){const{ done, value }=awaitreader.read();if(done)return;detachedDocument.write(value);element=iterator.nextNode();while(element){constisClosed=elementIsClosed(element);// Perform processingelement=iterator.nextNode();}}detachedDocument.close();// Process the root element if needed, document is closed so the root element is closed
This works for a few reasons:
document.write() and NodeIterator are both synchronous, so each chunk is written and processed synchronously.
Assuming the HTML is well-formed, the document and NodeIterator will both write and iterate depth-first. This allows the elementIsClosed() function to work reliably. If we find a nextSibling or a nextSibling of a parent, we know we encountered the close tag of the current element for something to be written after it.
This assumption only holds in the detached document, not the visible document. It also only holds if we strictly remove nodes from the detached document and never add or move elements.
It's possible to run similar logic on an open element that is streamed into the visible document, but needs to also keep track of the root node being streamed in the elementIsClosed() function and stop bubbling the parentElement at that point, since we expect nodes to exist outside of that root.
If an element is moved to the visible document when it is open, it will continue to stream into the visible document. The NodeIterator in the detached document is live, so it will not find any of the children streaming element. The processing step won't find any new elements on subsequent chunks (at first). Once the streaming element closes, the next element will be written after it into the detached document, and iterator.nextNode() will again return that element. This can also be used to determine that the streamed element is closed, if needed.
In some simple tests, a slower device can iterate a ~5000 node document in ~10ms with some basic conditional checks like attribute lookups.
Sorry, yes it's not directly related but still may be relevant. See my earlier comments for context. I originally commented with a similar use case looking for a MutationObserver close tag event. I haven't fully explored this for web components but it's possible part of the approach could be adapted.
I don't think there's an event when each chunk is written to check for completeness, though a new MutationObserver callback or a setInterval could be used.
Activity
Jamesernator commentedon Apr 30, 2019
Not sure if this is possible but would it be possible to simply capture the value of
childrenChangedCallbackimmediately after the element is constructed? Then one could easily enable an optimization that doesn't bother watching the children at all if the callback isn't actually provided.(This would be similar to the
iterator.nextchanges infor-ofloops that.nextis only captured once at the start of the loop).EDIT: It looks like the other methods already work like this by capturing the methods off the prototype (TIL).
rniwa commentedon Apr 30, 2019
All custom element callbacks are retrieved at the time of definition so such an optimization is already possible. See step 10 of https://html.spec.whatwg.org/multipage/custom-elements.html#dom-customelementregistry-define
annevk commentedon Apr 30, 2019
I support adding a children changed callback as that is indeed a primitive the DOM Standard provides and specifications and implementations use. (Firefox also has internal synchronous mutation observers, but nothing in the platform relies on them, though Firefox does currently use them for the
outputelement.)Before we add this however I'd like whatwg/dom#732 (review) solved. In particular, the primitive I referenced above isn't defined that well and some refactoring is needed. It'd be good to settle on the exact shape in private first before exposing it publicly.
(Note that this is effectively #550 btw.)
domenic commentedon Apr 30, 2019
As with #550, I do not support this if it is parser-specific. If it is just a CEReactions-time MutationObserver that only custom elements can install, then I'm open to investigating. In that case I think we should also seriously consider un-deprecating
DOMNodeRemoved/DOMNodeInsertedas an API shape, since that already exists in some browsers and we've needed to spec it properly for some time.justinfagnani commentedon Apr 30, 2019
I would love it to be a bit more than that, in that it observes projected children as well. I know that's covered
slotchange, but currently you need to combineslotchangeand a MO to implement "effective children changed".rniwa commentedon Apr 30, 2019
I don't think observing the assigned slot should be conflated with this API.
rniwa commentedon Apr 30, 2019
A common ask that keeps coming up is the ability to know when a child node has been inserted & updated: e.g. #765, #619, #615
To do this, just knowing when a child is inserted or removed isn't quite enough due to async / out-of-order upgrading. Perhaps we need both
childChangedCallbackandchildDefinedCallbackthe latter of which gets called when a child node is inserted & upgraded / defined.Also see whatwg/dom#662
caridy commentedon May 1, 2019
@rniwa do you foresee this as something that can be observed in a custom element or a more low level API that can be applied to any element? It is not clear from the title or description.
rniwa commentedon May 1, 2019
I think this needs to be a custom element reaction callback.
caridy commentedon May 1, 2019
That's probably limiting. I feel that this is in the same boat as the connect/disconnect reaction that we were asking for last week during the F2F, something a lot more generic.
Now, if we were to add a new reaction callback, will that callback be invoked even when the CE is not connected to the DOM? e.g.:
rniwa commentedon May 1, 2019
For general nodes, you can just use MutationObserver. If you wanted it sooner, then that's a discussion that has to happen in whatwg/dom#533
You mean when it's not connected to a document? If so, then yes. There is no reason to restrict this
childChangedCallbackto the connected nodes.112 remaining items
silverwind commentedon Mar 6, 2024
To me it seems to reliably access children in
connectedCallback, one has to check for both existing children (which is the case when the element is appended to the DOM via.innerHTMLor similar methods like Vue does it), and for regular DOM content where the children will be available after achildListmutation. Related demos.Honstly, it seems way to much boilerplate for such a simple and common use case.
patricknelson commentedon Mar 6, 2024
Just to clarify @silverwind it looks like your code is only for change events, and even then, only on the first change and doesn't cover the use case of indicating when the parser has completed parsing and appending children of a particular element on the DOM.
silverwind commentedon Mar 6, 2024
Yes, in this limited case I'm only interested in getting the reference to a mandatory child element. It will not be removed/added again ever after.
mfreed7 commentedon Mar 28, 2024
Another use case (for builtin elements) is source selection for
<video>. The conclusion on that issue seems to be that the best behavior is indeed to wait for the end tag before making a source selection. If that conclusion sticks, it'll be another instance of something a built-in element can do that a custom element cannot, because of the lack of the API this issue proposes.mangelozzi commentedon Mar 31, 2024
Say a component has many children, is there any chance the parser may connect the component after parsing some of the children, i.e. not all of them. It appears to this code assumes that all the children exist, or none of them at the time the
connectedCallbackruns. (I am not sure if this is the case?).WebReflection commentedon Apr 1, 2024
if you define your component at the end of the page you are 100% sure you can access its children and everything else as it gets just "promoted" as CE ... if you define your component AOT (which is 90% of what libraries do instead of lazy dafining their components only when needed/encountered) you are 100% sure (last time I've checked) the
connectedCallbackwill trigger instantly afterattributeChangedCallbackin case it was defined and the attribute is observed and encountered ... at that point the browser hasn't parsed yet the content of that element so you'll fallback with MutationObserver for children which guarantees nothing but usually it works "good enough".The whole issue is to have something that never fails and that can be used in all circumstances and definition time, something that while streaming a document will signal via
closedCallbackthat its ending has been encountered, something that even with lazy / late definitions will still trigger after theconnectedCallback.The problem raised in here is that in some streaming scenario the browser might already consider the element closed ... add people with "smart suggestions" like "don't need to close a
<p>or a<li>" 'cause the browser does that for you, see early hacks on never closing a<body>because the browser does that for you (and the legend say it's faster in doing so) and so on ... so the issue remains and solutions are all awkward in a way or another, or really not applied via lazy custom elements definition, something I've explored ages ago, something that works and never suffers the issue itself but developers don't like it for other reasons (FOUC or other related shenanigans that might be indeed a concern specially with 100% ShadowDOM based components).Sleepful commentedon Apr 3, 2024
I wonder if simply using the
deferattribute on<script>helps?I suppose it helps if the Component has not been registered already, but it might not help if it already registered.
Couldn't components have a similar
deferquality?mangelozzi commentedon Apr 4, 2024
Often you have components that need to be loaded quickly, e.g. if they are above the fold. Putting them last on the page does not work in this case. It's kind of like putting your stylesheets just your closing
</body>.For now I make a function that handles slotted children, that function has to be idempotent.
When the component is connected:
slotchange, that calls this function,this.addEventListener('slotchange', this.slotChangeHandler.bind(this))setTimeout(this.slotChangeHandler.bind(this))This handles the situation when the children are added before the component can initialise, and when they are slotted after it has been initialised. A bit clunky but don't know of any better.
nickcoury commentedon May 1, 2024
Updating on my case of streaming into a detached document and selectively moving nodes to the visible document. I found a much more efficient solution that also reliably identifies the closing tag by skipping the MutationObserver altogether and using a NodeIterator instead. Something similar might be possible for other use cases. Rough solution:
This works for a few reasons:
In some simple tests, a slower device can iterate a ~5000 node document in ~10ms with some basic conditional checks like attribute lookups.
WebReflection commentedon May 2, 2024
@nickcoury it's a great solution and thank sfor sharing but this also solves nothing and it's fully unrelated with Web Components, right?
nickcoury commentedon May 2, 2024
Sorry, yes it's not directly related but still may be relevant. See my earlier comments for context. I originally commented with a similar use case looking for a MutationObserver close tag event. I haven't fully explored this for web components but it's possible part of the approach could be adapted.
I don't think there's an event when each chunk is written to check for completeness, though a new MutationObserver callback or a setInterval could be used.
noamr commentedon Oct 19, 2026
Please see explainer for proposed solution: https://github.com/WICG/declarative-partial-updates/blob/main/parser-mutation-records-explainer.md
It tries to cover a lot of ground and address what's discussed here.
noamr commentedon Nov 5, 2026
See whatwg/html#13198 for active proposal following TPAC.
patricknelson commentedon Nov 5, 2026
@noamr do you have an updated URL?
noamr commentedon Nov 5, 2026
https://github.com/WICG/declarative-partial-updates/blob/main/parse-end-mutation-observer-explainer.md