A custom element can be defined before it appears on a page. Its connectedCallback() runs when the element is added to the document DOM, making it a useful place to start work that depends on the page: reading attributes, creating content, and finding child elements. Inside the method, this refers to the custom element itself. section 2.4 section 4.2
Listing 4.1. Testing when our connectedCallback is called
<script>
class MyCustomTag extends HTMLElement {
connectedCallback() {
alert('hi from MyCustomTag'); #1
this.innerHTML = '<h2>'+ this.getAttribute('title') +
'</h2><button>click me</button>';
}
}
if (!customElements.get('my-custom-tag')) {
customElements.define('my-custom-tag', MyCustomTag);
}
</script>
<style>
my-custom-tag {
background-color: blue;
padding: 20px;
display: inline-block;
color: white;
}
</style>
<body>
<my-custom-tag title="Another title"></my-custom-tag>
</body>
A small custom element reads its title attribute and creates a header and button when it connects. Remove its tag from the body and the connection alert does not appear. section 4.2
Try the timing in the console: createElement('my-custom-tag') constructs an element, but does not connect it. Append that element to document.body, and connectedCallback() runs. A constructor runs earlier; it can initialize properties, but it is not the place to build children in the page DOM or rely on markup attributes. section 4.2 section 12.1
Build a photo carousel on connection
A carousel reads its title, author, and comma-separated photos attributes in connectedCallback(). It creates the header, image container, and navigation buttons with innerHTML, shows the first photo, then attaches click listeners to the buttons. Each step uses DOM nodes or inputs available once the element is on the page. section 2.6
Connection need not be a one-time event: an element can be removed and appended again. If initialization must happen only once, guard it with a property before rendering content or mapping child nodes. Shadow DOM offers another option: its root can be created in the constructor and used there, while a component relying on the page DOM should defer that work to connectedCallback(). Other lifecycle hooks serve different jobs, including attributeChangedCallback for watched attributes and disconnectedCallback for cleanup. section 4.2 section 12.1 section 4.0
