如何在Firefox中使用自定义元素?

Dav*_*man 7 html javascript firefox html5

我有这个基本的自定义元素示例.它适用于Chrome,但不适用于Firefox.有没有办法让它在Firefox中运行(没有聚合物,但可能是某种填充剂)?

我也dom.webcomponents.enabled没有成功启用旗帜.


更新:

由于这已经解决了,我创建了一个存储库,其中包含完整的代码:https: //github.com/peplow/webcomponent-example/


自定义元素html文件:

<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>
Run Code Online (Sandbox Code Playgroud)

文件使用位置:

<!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>
Run Code Online (Sandbox Code Playgroud)

Men*_*ndy 12

截至2018年6月,可以通过以下步骤启用Firefox对自定义元素的支持

  1. 在搜索栏中输入about:config.
  2. 搜索dom.webcomponents.shadowdom.enabled单击以启用.
  3. serch dom.webcomponents.customelements.enabled单击以启用.

希望这有助于那里的人.

更新:现在,自Firefox 63以来,默认情况下Firefox中支持自定义元素.


小智 9

Firefox尚未发布自定义元素v1,这是最新的标准,它是指定customElements.define()元素的方式(与使用的v0相反,而Firefox中document.registerElement()dom.webcomponents.enabled标志可用).

Chrome是目前唯一支持自定义元素v1的浏览器,但所有其他主流浏览器都支持它.

Firefox有一个针对Custom Elements v1支持的开放式错误.

与此同时,您最好的选择是将Custom Elements v1 Polyfill用于不支持它的浏览器.您可以使用功能检测Custom Elements v1支持'customElements' in window.