Update 2024
Full blogpost:
Update March 2023
Note: this works because in the next tick your N (not all!) DOM elements IN lightDOM will have been parsed.
for (app.) N > 1000 you will run into trouble, as the delay will end before all N Elements are parsed.
So either add (about 20 lines) of code that actually checks all lightDOM is parsed. (but since your DOM is then suffering Obesitas, you will probably also have other performance problems)
Or just keep the N amount of DOM elements inside lightDOM small.
Ofcourse any DOM you add later, after parsing, doesn't affect anything (when the connectedCallback
doesn't fire)
Update March 2021:
FireFox bug fixed, now behaves the same as Chromium and Safari.
That means waiting for the JS EventLoop to be empty (with setTimeout
or requestAnimationFrame
) in the connectedCallback
is now a cross-browser method
connectedCallback(){
setTimeout(()=>{
// can access lightDOM here
}); // ,0 not required
}
What the heck is the Event Loop? - Philip Roberts
https://www.youtube.com/watch?v=8aGhZQkoFbQ
Update Oct. 28 2020:
Now reported by Mozilla engineer Anne van Kesteren as a bug in FireFox:
FireFox invokes the connectedCallback too late:
https://bugzilla.mozilla.org/show_bug.cgi?id=1673811
First post May. 2020:
Bitten again by this Chrome Element upgrade issue, after spending a week in FireFox.
Forgot to wrap code in a setTimeout before delivering to Chromium browsers.
FireFox prints: ABCD
Chromium prints: ADCD
Question: Why the difference?
<script>
customElements.define('my-element', class extends HTMLElement {
connectedCallback() {
console.log(this.innerHTML);// "A" in FireFox, "" in other Browsers
if (this.innerHTML == "A")
this.innerHTML = this.innerHTML + "B";
else
setTimeout(() => this.innerHTML = this.innerHTML + "D");
}
})
</script>
<my-element>A</my-element><my-element>C</my-element>
Related answers over the past years:
Update #1
- Apple/Safari: prints: ADCD (same as Chromium)
note: Chromium Blink engine is a fork of Apples (WebKit)WebCore code!!
Update #2
With Supersharps reference we found the related threads:
(2016) connectedCallback timing when the document parser creates custom elements
https://github.com/w3c/webcomponents/issues/551(2019) Need a callback for when children changed or parser finished parsing children
https://github.com/w3c/webcomponents/issues/809
connectedCallback
is what it says.. Element is connected and available. If the spec is unclear I would say Mozilla got it right. @Berniev, code is per example to show the difference in Browsers; Chromium/Safari requiring thesetTimeout
... since the error is also in Safari I suspect a deeper down/not Custom Element related issue .. because Chromiums Blink engine(2013) is a fork of Apples (WebKit)WebCore code. – HeisserconnectedCallback
trigger was wrong and has been fixed by Mozilla in March 2021 – Heisser