[WICG/webcomponents] Preventing re-renders prior to first call to `connectedCallback()` (Issue #1081)

In my custom components with observable attributes, I've noticed that `attributeChangedCallback()` is called multiple times before `connectedCallback()` is called.  Even though `connectedCallback()` hasn't been called yet, the value of `isConnected` in the earlier `attributeChangedCallback()` calls is true.  This occurs when a custom element is defined directly on the HTML page.  

The problem with this is there is no flag I can check to prevent unnecessarily re-rendering the element content before all attributes are initialised.

E.g.:

```html
<body>
  <my-custom-element attr1="a" attrr2="b" attr3="c"
</body>
```

The example component may look like this:

```js
class MyCustomElement extends HTMLElement {

  static get observedAttributes() {
    return ["attr1", "attr2", "attr3", "attr4", /* ... etc */ ];
  }

  connectedCallback() {
    this.render();
  }

  attributeChangedCallback(name, oldValue, newValue) {
    this.render();
  }

  render() {
    // this doesn't prevent any unnecessary re-rerendering because the element is already connected
    // even though connectedCallback() hasn't been called yet
    if (!this.isConnected) return;

    this.innerHTML = renderFunction.render(this.attributes)
  }
}
```

In this example, `attributeChangedCallback()` is called three times, and `this.isConnected` is `true` each time.  Finally, `connectedCallback()` is called.

This is problematic because I want to prevent unnecessary (re-)rendering of the element content until all the attributes defined in the HTML have been initialised due to the expense of computing the content for the element.

Now, I can manually add a flag and set it to true when `connectedCallback()` and false when `disconnectedCallback()` is called.  But I'm pretty sure every developer using web components would want/need this flag, so it makes sense for this to be part of the web component specification.

Ideally, I would like one or both of:
* A flag that is `false` before the call to `connectedCallback()` and `true`  after the initial calls to `attributeChangedCallback()` for each of the defined attributes.
  * An appropriate flag name might be `attributesInitialised` or `attributesInitialized`
* A callback that gets called between the initial calls to `attributeChangedCallback()` and the call to `connectedCallback()`
  * An appropriate callback name might be `attributesInitialisedCallback` or `attributesInitializedCallback`




-- 
Reply to this email directly or view it on GitHub:
https://github.com/WICG/webcomponents/issues/1081
You are receiving this because you are subscribed to this thread.

Message ID: <WICG/webcomponents/issues/1081@github.com>

Received on Wednesday, 16 October 2024 21:30:21 UTC