Custom Elements 是 Web Components 的核心,需继承 HTMLElement、含短横线命名,用 customElements.define() 注册;构造函数必须调用 super() 初始化 this,attributeChangedCallback 仅响应 observedAttributes 中声明的属性变更,且受浏览器兼容性与 DOM 结构限制。

Custom Elements 是 Web Components 的核心之一,它允许你定义自己的 HTML 标签,但不是靠封装或模拟,而是真正注册进浏览器的 DOM 系统——这意味着 document.createElement('my-button') 能返回合法元素,instanceof 会通过校验,且能被 querySelector、框架的 ref、甚至原生表单逻辑识别。
如何用 customElements.define() 注册一个自定义元素
必须继承 HTMLElement(或其子类如 HTMLButtonElement),且类名中必须含短横线(-),这是强制语法限制,否则抛出 DOMException: The element name must contain a hyphen。
- 类不能是匿名函数或箭头函数,必须有命名(哪怕只是
class MyCard extends HTMLElement) - 注册前必须先声明类,顺序不能颠倒;若重复注册同一名称,会报错
Failed to execute 'define' on 'CustomElementRegistry': the name "x-foo" has already been used - 名称不能以
x-开头再加短横线(如x-foo-bar合法,x--foo不合法),也不能是保留名(如html、slot、template)
class MyCounter extends HTMLElement {
constructor() {
super();
this.count = 0;
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
`;
}
connectedCallback() {
this.shadowRoot.querySelector('button').addEventListener('click', () => {
this.count++;
this.shadowRoot.querySelector('button').textContent = `${this.textContent}: ${this.count}`;
});
}
}
customElements.define('my-counter', MyCounter);
为什么必须用 constructor + super()?
因为 Custom Element 构造函数在 DOM 初始化阶段被调用(比如解析 HTML 字符串时),此时元素尚未插入文档,也无父节点。不调用 super() 会导致 this 未初始化,后续所有操作(如 attachShadow、setAttribute)都会失败,并静默报错或直接崩溃。
-
connectedCallback和disconnectedCallback可以安全访问this.parentNode,但constructor里永远不能 -
attributeChangedCallback的触发前提是:该属性在observedAttributes中声明,且元素已定义完成——也就是说,它不会在constructor执行期间触发 - 不要在
constructor里调用this.innerHTML或读取this.children,它们为空;应改用slot或innerHTML写入 shadow DOM
如何让自定义元素支持 HTML 属性并响应变更
仅靠 setAttribute 不会自动触发更新,必须显式监听属性变化。浏览器只会在属性值字符串发生变化时调用 attributeChangedCallback,且仅限于 observedAttributes 返回的数组中列出的属性名。
立即学习“Java免费学习笔记(深入)”;
- 属性名自动转为小写(
My-Prop→my-prop),所以observedAttributes必须写小写形式 - 若属性初始值来自 HTML(如
),attributeChangedCallback会在connectedCallback前触发一次 - 注意:布尔属性(如
disabled)的变更,newValue是""(空字符串)而非true;需用this.hasAttribute('disabled')判断
class MyInput extends HTMLElement {
static get observedAttributes() {
return ['value', 'disabled'];
}
attributeChangedCallback(name, oldValue, newValue) {
switch (name) {
case 'value':
this.input.value = newValue || '';
break;
case 'disabled':
this.input.disabled = this.hasAttribute('disabled');
break;
}
}
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = ``;
this.input = this.shadowRoot.querySelector('input');
}
}
customElements.define('my-input', MyInput);
使用时要注意哪些兼容性与陷阱
Chrome / Edge / Safari 原生支持良好,Firefox 从 63+ 支持,但 IE 完全不支持(无 polyfill 可完美还原行为)。即便现代浏览器,也有几个容易忽略的点:
- 自定义元素无法直接作为
的子元素(如
放在里)——浏览器会把它“提升”到 table 外,破坏结构;必须用is语法:- 服务端渲染(SSR)时,若 JS 未加载,自定义元素会表现为未知标签,样式和交互全部失效;建议配合
customElements.whenDefined()做降级处理- 若元素内使用了
slot,且宿主元素有innerHTML设置,内容不会自动投射——必须等connectedCallback触发后才生效最常被跳过的一步:没检查是否已定义就重复
define,尤其在模块热更新或微前端场景下。上线前务必加一层守卫:if (!customElements.get('my-card')) { customElements.define('my-card', MyCard); }真正的难点不在语法,而在生命周期节奏——什么时候能读 DOM、什么时候能改样式、什么时候能发事件,全都取决于你对
constructor/connectedCallback/attributeChangedCallback三者触发时机和约束条件的理解是否精确。 - 服务端渲染(SSR)时,若 JS 未加载,自定义元素会表现为未知标签,样式和交互全部失效;建议配合











