我正在使用web组件的“自定义元素”功能,需要支持旧的浏览器(火狐v60),所以不是通过webcomponent-loader.js加载所有的多填充。基于特征检测的延迟加载自定义元素detection
(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位)的页面中显示或加载
发布于 2019-04-22 21:47:08
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>有关详细信息,请参阅:
发布于 2019-04-23 02:23:14
只有在实现了自定义元素时,才能扩展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);
}
};https://stackoverflow.com/questions/55795053
复制相似问题