我正在尝试创建新的自定义元素。
我有一个非常简单的 html 索引文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="dist/webcomponents-lite.js"></script>
</head>
<body>
<h1>WebComponents</h1>
<hello-world></hello-world>
<script src="src/components/hello-world.js"></script>
</body>
</html>
我的hello-world 组件如下:
class HelloWorldElement extends HTMLElement {
constructor(){
super()
this.innerHTML = `<h1>Hello Meetup !</h1>`;
}
connectedCallback(){
console.log("I'm here!");
}
disconnectedCallback(){
console.log("I'm gone!");
}
}
window.customElements.define(
'hello-world',
HelloWorldElement);
此代码片段在 Chrome 和 Safari 中运行良好。
我添加了 webcomponents-lite.js 导入以添加对其他浏览器的支持。
然而,当尝试在 Firefox 中运行代码时,出现以下错误:
too much recursion
[Learn More]
webcomponents-lite.js:93:170
我在网上找到的关于可能发生的事情的信息很少。
我想我正在遵循 polyfills page 中解释的推荐路径来自 Web 组件网站。
知道发生了什么事吗?
谢谢
编辑:
我可以通过在 firefox 配置中启用 dom.webcomponents.customelements.enabled 和 dom.webcomponents.enabled 并删除 polyfill 来显示自定义元素,但这显然不是生产所需的东西。
最佳答案
错误是由于您在其构造函数
中修改了自定义元素的内部 HTML 内容,这是意外的,因此不应该这样做。
相反,您应该在之后执行此操作,例如在 connectedCallback()
方法中。
或者,如果您想在 constructor
中定义内容,您应该将其插入到 Shadow DOM 中。
注意:自定义元素 polyfill 有效地包含在 webcomponents-lite.js 中。
关于javascript - 使用自定义元素时 Firefox 中的递归过多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47715192/