Daveman Daveman - 10 days ago 5
HTML Question

How to get custom elements working in Firefox?

I have this basic custom element example. It is working in Chrome, however not in Firefox. Is there a way to get it working in Firefox (without polymer but maybe some kind of polyfill)?

I also enabled the

dom.webcomponents.enabled
flag without any success.




Update:



Since this is solved, I created a repository, with the complete code:
https://github.com/peplow/webcomponent-example/




Custom element html file:

<template id="template">
<button id="button">Hallo</button>
<style media="screen">
button{
color:red;
}
</style>
</template>

<script>
var localDoc = document.currentScript.ownerDocument;
class toggleButton extends HTMLElement{

constructor(){
super();
this.shadow = this.attachShadow({mode: 'open'});
var template = localDoc.querySelector('#template');
this.shadow.appendChild(template.content.cloneNode(true));

this.shadow.querySelector('button').onclick = function(){
alert("Hello World");
}
}

static get observedAttributes() {return ['name']; }

attributeChangedCallback(attr, oldValue, newValue) {
if (attr == 'name') {
this.shadow.querySelector('#button').innerHTML = newValue;
}
}

}

customElements.define('x-toggle', toggleButton);
</script>


File where it is used:

<!DOCTYPE html>
<html>
<head>
<link rel="import" href="element.html">
<meta charset="utf-8">
</head>
<body>
<x-toggle name="Hello World"></x-toggle>
</body>
</html>

Answer

Firefox has not yet shipped Custom Elements v1, which is the latest standard and is what specifies customElements.define() as the way to define an element (as opposed to v0 which used document.registerElement() and is what is available with the dom.webcomponents.enabled flag in Firefox).

Chrome is currently the only browser that supports Custom Elements v1 natively, but all other major browsers are supportive of it.

Firefox has an open bug for Custom Elements v1 support.

In the meantime, your best bet is to use the Custom Elements v1 Polyfill for browsers that don't support it. You can feature-detect Custom Elements v1 support with 'customElements' in window.

Comments