Skip to content

Need a callback for when children changed or parser finished parsing children #809

Open

Description

@rniwa

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.

Activity

  1. Jamesernator commented on Apr 30, 2019

    @Jamesernator

    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).

  2. rniwa commented on Apr 30, 2019

    @rniwa
    CollaboratorAuthor

    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

  3. annevk commented on Apr 30, 2019

    @annevk
    Collaborator

    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.

    (Note that this is effectively #550 btw.)

  4. domenic commented on Apr 30, 2019

    @domenic
    Collaborator

    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.

  5. justinfagnani commented on Apr 30, 2019

    @justinfagnani
    Contributor

    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".

  6. rniwa commented on Apr 30, 2019

    @rniwa
    CollaboratorAuthor

    I don't think observing the assigned slot should be conflated with this API.

  7. rniwa commented on Apr 30, 2019

    @rniwa
    CollaboratorAuthor

    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.

    Also see whatwg/dom#662

  8. caridy commented on May 1, 2019

    @caridy

    @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.

  9. rniwa commented on May 1, 2019

    @rniwa
    CollaboratorAuthor

    @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.

  10. caridy commented on May 1, 2019

    @caridy

    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.:

    const ce = document.createElement('x-foo');
    ce.appendChild(document.createElement('p'));
  11. rniwa commented on May 1, 2019

    @rniwa
    CollaboratorAuthor

    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.

  12. 112 remaining items

  13. silverwind commented on Mar 6, 2024

    @silverwind

    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.

    connectedCallback() {
      if (this.children.length) 
        // access this.children
      } else {
        const observer = new MutationObserver(() => {
          observer.disconnect();
          // access this.children
        }).observe(this, {childList: true});
      } 
    }

    Honstly, it seems way to much boilerplate for such a simple and common use case.

  14. patricknelson commented on Mar 6, 2024

    @patricknelson

    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.

  15. silverwind commented on Mar 6, 2024

    @silverwind

    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.

  16. mfreed7 commented on Mar 28, 2024

    @mfreed7

    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.

  17. mangelozzi commented on Mar 31, 2024

    @mangelozzi

    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.

    connectedCallback() {
      if (this.children.length) 
        // access this.children
      } else {
        const observer = new MutationObserver(() => {
          observer.disconnect();
          // access this.children
        }).observe(this, {childList: true});
      } 
    }

    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?).

  18. WebReflection commented on Apr 1, 2024

    @WebReflection

    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).

  19. Sleepful commented on Apr 3, 2024

    @Sleepful

    I wonder if simply using the defer attribute 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 defer quality?

  20. mangelozzi commented on Apr 4, 2024

    @mangelozzi

    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:

    1. I setup a eventHandler for slotchange, that calls this function, this.addEventListener('slotchange', this.slotChangeHandler.bind(this))
    2. 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.

  21. nickcoury commented on May 1, 2024

    @nickcoury

    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.
    function elementIsClosed(element) {
      let currentElement = element;
      while (currentElement) {
        if (currentElement.nextSibling) return true;
        currentElement = currentElement.parentElement;
      }
      return false;
    }
    
    const iterator = new NodeIterator(detachedDocument, NodeFilter.SHOW_ELEMENT);
    let element;
    const response = await fetch("https://example.com");
    const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
    
    while (true) {
      const { done, value } = await reader.read();
      if (done) return;
      detachedDocument.write(value);
    
      element = iterator.nextNode();
      while (element) {
        const isClosed = elementIsClosed(element);
        // Perform processing
        element = 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:

    1. document.write() and NodeIterator are both synchronous, so each chunk is written and processed synchronously.
    2. 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.
    3. 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.
    4. 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.
    5. 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.

  22. WebReflection commented on May 2, 2024

    @WebReflection

    @nickcoury it's a great solution and thank sfor sharing but this also solves nothing and it's fully unrelated with Web Components, right?

  23. nickcoury commented on May 2, 2024

    @nickcoury

    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.

  24. noamr commented on Oct 19, 2026

    @noamr

    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.

  25. noamr commented on Nov 5, 2026

    @noamr

    See whatwg/html#13198 for active proposal following TPAC.

  26. patricknelson commented on Nov 5, 2026

    @patricknelson

    Please see explainer for proposed solution: https://github.com/WICG/declarative-partial-updates/blob/main/parser-mutation-records-explainer.md

    @noamr do you have an updated URL?

  27. noamr commented on Nov 5, 2026

    @noamr
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