4 ms·
The constructor is a part of the lifecycle, and always has been. It wasn't abandoned. The lifecycle of custom elements reflects the behavior of the HTML parser
by spankalee 1y ago
The constructor is a part of the lifecycle, and always has been. It wasn't abandoned.
The lifecycle of custom elements reflects the behavior of the HTML parser and DOM APIs. Attributes aren't consistently available in the constructor because the HTML parser is streaming and may yield to the main thread at any time. So the element is constructed first, possibly before attributes are parsed. Attribute also aren't available because when element are constructed imperatively they will never have attributes at first, ie:
// ctor is called, no attributes!
const el = document.createElement('my-element');
// now there will be an attribute:
el.setAttribute('width');
You also shouldn't ever consider attributes to be fixed in a web component, since they may be added and removed at any time, and of course may never be set in the first place. You should implement attributeChangedCallback() and give your element defined behavior for any set of possible attributes.
Or you can use a helper library like Lit which does let you declare and consume your attributes via decorators.
- shortrounddev2 1y agoI understand all these things, I think they are weaknesses. They make web components less generally useful, and really only useful for one thing. Constructors are only useful for dependency injection.