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

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.


In most cases, the problem will be that you are trying to create an element that will magically have attributes when it is first added to the DOM, which is not expected behaviour for HTML elements. Think about:

const div = document.createElement("div");
document.body.append(div);

For divs, and all other element types, you will never have a DOM element created that already has attributes like . Classes and all other attributes are always added after the element has been created with .createElement(), like:

const div = document.createElement("div");
div.className = "random-class";
document.body.append(div);

.createElement() will never create an element that already has attributes such as classes. The same applies for custom elements. It would therefore be unexpected if:

const myElement = document.createElement("my-element");
document.body.append(myElement);

added a DOM element like <my-element class="unexpected-attribute"></my-element>. You shouldn't be adding attributes like classes to the actual custom element. If you want to add attributes and styling, you should attach children to your element (in a shadowRoot for a web component), for example a div to which you can add whatever attributes you want, whilst leaving your actual custom element free of attributes.

Example:

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

As a web component:

class SquareLetter extends HTMLElement {
    constructor() {
        super();
        this.attachShadow({mode: "open"});
        const div = document.createElement("div");
        div.className = getRandomColor();
        this.shadowRoot.append(div);
    }
}
customElements.define("square-letter", SquareLetter);