hankchiutw
hankchiutw

Reputation: 1662

Why does the connectedCallback not work for native HTMLElement(not custom elements)?

I know connectedCallback is for custom elements. I wonder how to make the following snippet work:

const div = document.createElement('div');
div.connectedCallback = () => console.log('connected!');
document.body.appendChild(div);
// how to make it print "connected!" here?

There are guys making DOM/connectedCallback which utilizes the MutationObserver.

MutationObserver should work for this scenario, but why does W3C not make connectedCallback work for HTMLElement? for performance?

I found there is a read-only property isConnected but it's not helpful for detecting connected or not.

Upvotes: 1

Views: 1548

Answers (1)

Remember, HTML is backward compatible with previous versions

You would have to time-travel to HTML 1.0 (1993) to change behaviour into what you want.

New functionality is mainly added with APIs. That is why it is called the Custom Elements API..
it doesn't change HTML, Browsers add new functionality, you can call from JavaScript

Thus connectedCallback is a method of a Custom Element (which extends from HTMLElement)

So the only way to detect mutations on an HTMLElement is using the: MutationObserver API

connectedCallback does not mean the lightDOM is ready; it fires on the opening tag; there could be a very large HTML structure inside which hasn't loaded and parsed yet.

Easiest method to wait till your lightDOM elements are created, is to continue when the EventLoop is empty:

connectedCallback(){
 setTimeout(()=>{  // or requestAnimationFrame()
   // lightDOM is ready now
 });
}

Upvotes: 3

Related Questions