我将如何异步导入自定义 Web 组件?

How would I import a custom web component asynchronously?

我已将我的自定义输入元素(表单的现代文本输入)制作成 Web 组件。我为实现它而制作的 .js 文件包含三个部分。

HTML模板:

const textInputTemplate = document.createElement('text-input-template');
textInputTemplate.innerHTML =
`
<div class="text-input-container">
    <!--Irrelevant-->
</div>
`;

元素的Class声明:

class textInput extends HTMLElement {

    static get observedAttributes() {
        return ['readonly'];
    }

    constructor () {
        super();
        // Shadow root
    } // End of constructor()

    connectedCallback () {
        // Custom attributes
    } // End of connectedCallback()

    disconnectedCallback () {
        // Remove event listeners
    } // End of disconnectedCallback()

    attributeChangedCallback(attribute, oldValue, newValue) {
        // Updatable attributes: readonly
    } // End of attributeChangedCallback()   
}

最后,将自定义元素关联到标签名称的方法:

window.customElements.define('text-input', textInput);

问题: 我担心使用 <script src="./module-name"> 低效 可能导致错误 因为它在页面的其余部分之后同步加载加载。因此,我想知道是否有一种 cleaner/more 专业方法可以异步导入 Web 组件,而无需将整个模块粘贴到这样的函数中:

export function textInput { // insert entire modules contents here }

因为 Web 组件需要模块的所有三个部分才能工作,所以我不能只导出 Web 组件 class。

我知道这是一个老问题,但没有得到解决,我也遇到过同样的问题,并且在以这种方式加载脚本时就像包含 async 一样简单:

<script src="./module-name" async>

你可以查看here or here

在哪里说,例如:

When present, it specifies that the script will be executed asynchronously as soon as it is available.

If the async attribute is present, then the classic script will be fetched in parallel to parsing and evaluated as soon as it is available.

因此您不必担心锁定页面的其余部分,因为每个脚本都会尽快并行加载。