Failed to construct 'CustomElement' error when JavaScript file is placed in head

user7885142 picture user7885142 · May 7, 2017 · Viewed 11.6k times · Source

I have a custom element defined like so:

class SquareLetter extends HTMLElement {
    constructor() {
        super();
        this.className = getRandomColor();
    }
}
customElements.define("square-letter", SquareLetter);

When the JavaScript file is included in HTML <head> tag, the Chrome console reports this error:

Uncaught DOMException: Failed to construct 'CustomElement': The result must not have attributes

But when the JavaScript file is included before the </body> ending tag, everything works fine. What's the reason?

<head>
    <script src="js/SquareLetter.js"></script> <!-- here -->
</head>
<body>
    <square-letter>A</square-letter>
    <script src="js/SquareLetter.js"></script> <!-- or here -->
</body>

Answer

Jeremy picture Jeremy · May 8, 2017

The error is correct, and could occur in both cases. You're getting "lucky" because some current implementations of Custom Elements do not enforce this requirement.

The constructor for a custom element is not supposed to read or write its DOM. It shouldn't create child elements, or modify attributes. That work needs to be done later, usually in a connectedCallback() method (although note that connectedCallback() can be called multiple times if the element is removed and re-added to the DOM, so you may need to check for this, or undo changes in a disconnectedCallback()).

Quoting the WHATWG HTML specification, emphasis mine:

§ 4.13.2 Requirements for custom element constructors:

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. This is true even if the work is done inside a constructor-initiated microtask, as a microtask checkpoint can occur immediately after construction.

When you move the script to after the element in the DOM, you cause the existing elements to go through the "upgrade" process. When the script is before the element, the element goes through the standard construction process. This difference is apparently causing the error to not appear in all cases, but that's an implementation detail and may change.