WebComponents:Firefox自定义元素未显示

问题描述 投票:1回答:2

我正在使用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/[email protected]/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);
}
})()

加载时手动和firedWebComponentsReady事件。注册如下的元素

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位)的页面中显示或加载

javascript firefox web-component custom-element
2个回答
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>

欲获得更多信息:


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);
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.