whenDefined()
方法在
CustomElementRegistry
interface returns a
Promise
that resolves when the named element is defined.
Promise<> customElements.whenDefined(name);
Custom element name.
A
Promise
that resolves to
undefined
when the custom element is defined. If the custom element is already defined, the promise is resolved immediately.
| 异常 | 描述 |
|---|---|
SyntaxError
|
If the provided name is not a
valid custom element name
, the promise rejects with a
SyntaxError
.
|
此范例使用
whenDefined()
to detect when the custom elements that make up a menu are defined. The menu displays placeholder content until the actual menu content is ready to display.
<nav id="menu-container">
<div class="menu-placeholder">Loading...</div>
<nav-menu>
<menu-item>Item 1</menu-item>
<menu-item>Item 2</menu-item>
...
<menu-item>Item N</menu-item>
</nav-menu>
</nav>
const container = document.getElementById('menu-container');
const placeholder = container.querySelector('.menu-placeholder');
// Fetch all the children of menu that are not yet defined.
const undefinedElements = container.querySelectorAll(':not(:defined)');
const promises = [...undefinedElements].map(
button => customElements.whenDefined(button.localName)
);
// Wait for all the children to be upgraded,
// then remove the placeholder.
await Promise.all(promises);
container.removeChild(placeholder);
| 规范 | 状态 | 注释 |
|---|---|---|
|
HTML 实时标准
The definition of 'customElements.whenDefined()' in that specification. |
实时标准 | 初始定义。 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
whenDefined
|
Chrome
66
|
Edge
79
|
Firefox
63
|
IE 不支持 No |
Opera
53
|
Safari
10.1
|
WebView Android
66
|
Chrome Android
66
|
Firefox Android
63
|
Opera Android
47
|
Safari iOS
10.3
|
Samsung Internet Android
9.0
|
完整支持
不支持
实验。期望将来行为有所改变。
见实现注意事项。
用户必须明确启用此特征。