Webcomponents: Empty innerHTML/textContent in connectedCallback, but the actual content is rendered

Created on 28 Oct 2020  路  8Comments  路  Source: WICG/webcomponents

Sorry for possibly duplicating issue, please redirect to existing discussion (parsedCallback or etc.).

Just wanted to point out to obscure API aspect.

<script>
  customElements.define('x-x', class extends HTMLElement {
    connectedCallback() {
      console.log(this.innerHTML)
    }
  })
</script>

<x-x>123</x-x>

The element is rendered in DOM as 123, but innerHTML/textContent is empty. Is that rendered/API state mismatch correct? There seems to be no way to get access to what being actually rendered.

Expectation: it should either return innerHTML with factually rendered content, or if innerHTML is empty then it should not render 123.

custom-elements question

All 8 comments

This is expected. When x-x element is inserted into the document, the text node for 123 hasn't gotten inserted into the document / parsed yet.

Please let us know if the above doesn't answer your question.

FYI, FireFox does show/can access the .innerHTML content.
Other Browsers require a setTimeout to be able to work with DOM content in the connectedCallback

I filed https://bugzilla.mozilla.org/show_bug.cgi?id=1673811 on that. Note that setTimeout is absolutely the wrong approach here and might very well fire at the wrong time. You want to observe actual mutations to the tree using mutation observers.

Can you elaborate on _setTimeout is absolutely the wrong approach_

Doesn't setTimeout ensure code is run when the Eventloop is done/empty?

If the objective is to access (light)DOM content from the connectedCallback;
can setTimeout code run too early?

<my-element>Hello </my-element> ... connectedCallback(){ setTimeout(()=>{ this.innerHTML = this.innerHTML + "World!" }) }

Note, in FireFox the timeout is not required:

<my-element>Hello </my-element> ... connectedCallback(){ this.innerHTML = this.innerHTML + "World!" }
runs fine

Yeah, if bytes stream in slowly or some such the element end tag might not have been seen yet. What you are seeing in Firefox is a bug.

@annevk in case of <template is="x-template"> we can't setup childList observer in connectedCallback, because template doesn't get notified about inserted children.

@dy you can on template.content, no?

Was this page helpful?
0 / 5 - 0 ratings