假设已定义一个自定义元素,并使用CustomElements.whenDefined
函数检查何时发生:
customElements.whenDefined("foo-bar").then(console.log)
customElements.define("foo-bar", class {});
根据自定义元素规范(https://html.spec.whatwg.org/multipage/custom-elements.html#dom-customelementregistry-whendefined)和MDN文档(https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry/whenDefined),CustomElements.whenDefined
将由CustomElement的构造方法解析。但是,在chrome(86)或firefox(82)中运行上述代码时,它会记录undefined
。微软对此方法的类型定义(https://github.com/microsoft/TypeScript/blame/2d495b7f251511ba00bc0e3311de2090f92e79dd/lib/lib.dom.d.ts#L3513)也使用“ void”来解决。
({customElements.get("foo-bar")
确实可以正常工作并返回构造函数。)
有人知道为什么吗?