WebComponents:Firefox自定义元素未显示

时间:2019-04-22 13:19:29

标签: javascript firefox web-component custom-element

我正在使用Web组件的“自定义元素”功能,并且需要支持旧的浏览器(Firefox v60),所以与其通过webcomponent-loader.js加载所有polyfill来加载polyfill。基于特征检测的延迟加载的custom-elementpolyfill

(function() {
if(!window.customElements){
var ce = document.createElement('script');
ce.type = 'text/javascript';
ce.async = true;
ce.src = 'https://unpkg.com/@webcomponents/custom-elements@1.2.4/custom-elements.min.js';
/**

     * loading "customElement" polyfills wont't fire "WebComponentsReady" event, it will be called when we use
     * "webcomponent-loader.js" but it will load other polyfills("shadow-dom"), so loading the "customElements" polyfill alone
     * based on feature detection and firing "WebComponentsReady" event manually.
     */
  ce.onload = function() {
      document.dispatchEvent(
          new CustomEvent('WebComponentsReady', {bubbles: true}));
  };
  var st = document.getElementsByTagName('script')[0];
  st.parentNode.insertBefore(ce, st);
}
})()

并在加载事件后手动触发WebComponentsReady事件。注册如下元素

let registerElement = () => {
 if(!window.customElements.get(“wc-button")){
   window.customElements.define(‘wc-button', WCButton);
 }
};

if(window.customElements){
  registerElement();
 } else {
  document.addEventListener('WebComponentsReady', registerElement);
}

已触发WebComponentsReadygot,并且已在侦听器回调中调用它来定义/注册该元素,但是该元素并未在firefox60.6.1esr(64位)中显示或加载到页面中

2 个答案:

答案 0 :(得分:2)

webcomponents-loader.js为您进行功能检测 您不必等待WebComponentsReady事件,而是这样做

<script src="https://unpkg.com/@webcomponents/webcomponentsjs/webcomponents-loader.js"></script>
<script>
window.WebComponents.waitFor(() => {
   // do stuff that needs the polyfill
})
</script>

有关更多信息:

答案 1 :(得分:0)

仅当实现了自定义元素时,HTMLElement才可以扩展(可以在本地使用polyfill扩展)。

因此,只有在加载polyfill之后,才必须定义<wc-button>自定义元素类。

在您的示例中:

let registerElement = () => {
    if(!window.customElements.get("wc-button")){
         //define the WCButton class here
         class WCButton extends HTMLElement {
             //...
         }
         window.customElements.define(‘wc-button', WCButton);
    }
};