Javascript Vanilla JS web组件,包括<;头>;及<;车身>;

Javascript Vanilla JS web组件,包括<;头>;及<;车身>;,javascript,web-component,Javascript,Web Component,是否可以将头部和身体作为web组件的元素 我尝试了下面的示例,但web html放在正文中,而head是空的: index.html: <!doctype html> <html> <web-html></web-html> <script type="module" src="html.js"></script> </html> customElemen

是否可以将头部和身体作为web组件的元素

我尝试了下面的示例,但web html放在正文中,而head是空的:

index.html

<!doctype html>
<html>
    <web-html></web-html>
    <script type="module" src="html.js"></script>
</html>
customElements.define('web-html', class extends HTMLElement {
    constructor() {
        super();
        const template = document.createElement('template');
        template.innerHTML = `
            <head>
                <meta charset="utf-8" />
                <title> Index </title>
            </head>
            <body>
                <slot> ... </slot>
            </body>
        `;
        const shadowRoot = this.attachShadow({mode:'open'});
        shadowRoot.appendChild(template.content.cloneNode(true));
    };
});

html.js

<!doctype html>
<html>
    <web-html></web-html>
    <script type="module" src="html.js"></script>
</html>
customElements.define('web-html', class extends HTMLElement {
    constructor() {
        super();
        const template = document.createElement('template');
        template.innerHTML = `
            <head>
                <meta charset="utf-8" />
                <title> Index </title>
            </head>
            <body>
                <slot> ... </slot>
            </body>
        `;
        const shadowRoot = this.attachShadow({mode:'open'});
        shadowRoot.appendChild(template.content.cloneNode(true));
    };
});
customElements.define('web-html',类扩展了HtmleElement{
构造函数(){
超级();
const template=document.createElement('template');
template.innerHTML=`
指数
... 
`;
const shadowRoot=this.attachShadow({mode:'open'});
appendChild(template.content.cloneNode(true));
};
});

自定义元素必须包含在
元素中。因此,它不应包含任何
元素

因此,如果您想同时在
上包含内容,则需要以不同的方式进行:例如使用
document.head.appendChild()


此外,
必须是
的直接子元素,因此不能将它们包含在自定义元素中。

为什么要这样做?@LuketheGeek我希望避免重复头部