ampproject / ampproject/amphtml

Prevent calling #hasAttribute or #getAttribute in element constructor

Open
#10,058 7 comments 0 reactions 0 assignees View on GitHub
P3: When Possible Stale Type: Bug WG: runtime
Dominant language
JavaScript
Stars
14.9k
Forks
4.1k
PR merge metrics
No merged PRs in 30d

Description

follow up of #10045

**Reason**
customElement's `#createdCallback()` is called when the element is created, while `#connectedCallback()` is called when the element is first connected to DOM.

We construct an AMP Element in `createdCallback()`. Using DOM API in element's constructor is DOM API before adding element to DOM, thus should be forbidden.

**Failing Example**
In the following example, when `element.getAttribute()` is called before `#setAttribute()`
```
class AmpTest extends AMP.BaseElement {
constructor(element) {
this.url = element.getAttribute('url);
}
}
```

```
const ele = document.createElement('amp-test');
/** AmpTest constructor gets called when element is created. At this point `` element's attributes are not ready yet */
ele.setAttribute('url', 'fakeurl');
```

Contributor guide

Open the contributing guide

Research direction

Start by reading the follow-up issue #10045 and the AMP.BaseElement lifecycle around createdCallback() and connectedCallback(). Reproduce the failing example with AmpTest, then verify that element constructors no longer call hasAttribute() or getAttribute() before attributes are set.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
frontend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.