Vanilla JS Web 组件,包括 <head> 和 <body>

Vanilla JS web component including <head> and <body>

是否可以将 headbody 作为 Web 组件的元素包含在内?

我尝试了下面的例子,但是 web-html 被放在 body 里面,而 head 为空:

index.html:

<!doctype html>
<html>
    <web-html></web-html>
    <script type="module" src="html.js"></script>
</html>

html.js:

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));
    };
});

自定义元素必须包含在 <head><body> 元素中。因此它不应包含任何 <head><body> 元素。

因此,如果您想在 <head><body> 上都包含内容,则需要采用不同的方式:例如 document.head.appendChild()

此外,<head><body> 必须是 <html> 的直接子代,因此您不能将它们包含在自定义元素中。

Web 组件是 html 文档正文的一部分。当你想在头脑中加入 somphing 时,你必须通过 dom api 来做到这一点。但是你可以在不同的模板中做 head 的东西,然后将内容复制到 head 标签中。