Search code examples
javascriptecmascript-6web-componentpolyfillscustom-element

Custom Elements Illegal Constructor in FireFox


I have a CustomElement with the following constructor:

export default class SomeCustomElement extends HTMLElement {
    constructor(templateId) {
        super();
        this.insertTemplateInstance(templateId);
    }
    ...
}

I can register that Element in Chrome without any Problems.

But using Firefox with the polyfill loaded by webcomponents-loader.js from https://github.com/webcomponents/webcomponentsjs I get the ErrorMessage TypeError: Illegal constructor when calling super().

Does anybody know what is causing this?

Some more Background:

Registering of the custom Elements happens like this:

window.addEventListener("WebComponentsReady", function () {
    customElements.define(elementName, SomeCustomElement);
});

Solution

  • Use webcomponents-lite.js instead of webcomponent-loader.js if you don't want to have this kind of error, which is caused by the fact that the polyfills will be loaded asynchronously if you use webcomponents-loader.js.

    The example below works fine with Firefox (and every modern browser):

    class SomeCustomElement extends HTMLElement
    {
      constructor()
      {
        console.log( 'created' )
        super()
      }
    
      connectedCallback() {
        console.log( 'connected' )
        this.innerHTML = "Hello"
      }
    }
    
    customElements.define( 'c-e', SomeCustomElement ) 
    <script src=https://rawgit.com/webcomponents/webcomponentsjs/master/webcomponents-lite.js></script>
    
    <c-e></c-e>

    However if you still want to use webcomponents-loader.js, you'll have to insert your custom element definition in an external file, and load it with HTML Imports:

    <link rel="import" href="my-element.html">