问题
Here's a fiddle showing an error in console in Chrome 72 and Firefox 63:
https://jsfiddle.net/jr2z1ms3/1/
The code is:
<script>
customElements.define('test-element', class extends HTMLElement {
constructor() {
super()
Promise.resolve().then(() => {
this.setAttribute('foo', 'bar')
})
}
})
</script>
<test-element>test</test-element>
In Chrome the error is:
Uncaught DOMException: Failed to construct 'CustomElement': The result must not have attributes
In Firefox the error is:
NotSupportedError: Operation is not supported
If you comment the setAttribute
call, the error goes away in both browsers.
The following example illustrates changing attributes before an element is connected, which shows that it can be done with macrotasks, yet (unfairly) not with microtasks:
(working fiddle for snippet below)
customElements.define('test-element', class extends HTMLElement {
constructor() {
super()
setTimeout(() => {
this.setAttribute('foo', 'bar')
})
}
connectedCallback() {
console.log('foo attribute:', this.getAttribute('foo'))
}
})
const el = document.createElement('test-element')
console.log('no foo attribute:', el.getAttribute('foo'))
setTimeout(() => {
document.body.appendChild(el)
})
In the first example I am not setting the attribute in the constructor, I am deferring to a future microtask. So why are the browsers complaining? If this is intended as per spec, then does the spec have a "design bug"? Why should we not be able to do this?
based on answers below, I don't see why this limitation needs to be in place. A bad developer can still make a mess with or without this browser-engine limitation in place.
IMO, let devs decide (and document) how their custom elements work.
Is there some technical limitation that the browser otherwise can't overcome if we were to be able to set attributes in the contructor or a microtask after the constructor?
回答1:
According to the spec there are certain things you must never do in the constructor:
When authoring custom element constructors, authors are bound by the following conformance requirements:
A parameter-less call to super() must be the first statement in the constructor body, to establish the correct prototype chain and this value before any further code is run.
A return statement must not appear anywhere inside the constructor body, unless it is a simple early-return (return or return this).
The constructor must not use the document.write() or document.open() methods.
The element's attributes and children must not be inspected, as in the non-upgrade case none will be present, and relying on upgrades makes the element less usable.
The element must not gain any attributes or children, as this violates the expectations of consumers who use the createElement or createElementNS methods.
In general, work should be deferred to connectedCallback as much as possible—especially work involving fetching resources or rendering. However, note that connectedCallback can be called more than once, so any initialization work that is truly one-time will need a guard to prevent it from running twice.
In general, the constructor should be used to set up initial state and default values, and to set up event listeners and possibly a shadow root.
Several of these requirements are checked during element creation, either directly or indirectly, and failing to follow them will result in a custom element that cannot be instantiated by the parser or DOM APIs.
The problem with your example is that the Promise
is resolved immediately and is, thus, still in the constructor.
If you change your code to this:
customElements.define('test-element', class extends HTMLElement {
constructor() {
super()
setTimeout(() => {
this.setAttribute('foo', 'bar')
}, 100)
}
})
<test-element>test</test-element>
Then it works because the setTimeout
gets you out of the constructor.
回答2:
The spec mentions this:
This is true even if the work is done inside a constructor-initiated microtask, as a microtask checkpoint can occur immediately after construction.
来源:https://stackoverflow.com/questions/54857905/deferred-setattribute-call-in-custom-element-constructor-causes-dom-error-is-it