Master Custom Elements lifecycle callbacks, observedAttributes, shadow DOM encapsulation, and the customElements registry
0 / 5 completed
1 / 5
What does the connectedCallback lifecycle method do in a Custom Element?
connectedCallback: is invoked each time the custom element is appended to a document-connected element. Use it to set up event listeners, fetch data, or render shadow DOM content. The counterpart is disconnectedCallback for teardown logic when the element is removed.
2 / 5
How do you declare which attributes trigger attributeChangedCallback?
observedAttributes: is a static getter that returns an array of attribute names. Only changes to those attributes cause attributeChangedCallback(name, oldVal, newVal) to fire, avoiding performance overhead from observing every attribute on the element.
3 / 5
What is the purpose of attachShadow({ mode: 'open' }) in a Custom Element?
Shadow DOM: provides encapsulation by creating a separate DOM tree attached to the element. With mode: 'open' the shadow root is accessible via element.shadowRoot; with 'closed' it is not. Styles inside do not leak out and external styles do not bleed in.
4 / 5
What does customElements.whenDefined('my-element') return?
whenDefined(): returns a Promise that resolves when customElements.define() is called for the given tag name. This is useful for lazy-loading component scripts and running code only after upgrade, e.g. await customElements.whenDefined('my-button').
5 / 5
What is the role of the constructor in a Custom Element class?
Custom Element constructor: must call super() first. Use it to create the shadow root and initialise internal properties. Avoid accessing child elements or attributes here — the DOM upgrade may happen before the element is fully parsed, so those are unavailable until connectedCallback.