According to the HTML spec, only metadata content is allowed within the <head>
element. If a custom element is encountered during parsing, the document head is closed from that point onwards, and the rest is added to the document body. Therefore, if specific meta tags need to be present in the head, they cannot be replaced with a single custom element.
A better approach is to explore methods for abstracting and customizing the tags at the HTML templating level.
However, it's worth noting that while the HTML spec restricts the content of the <head>
element to metadata, modern browsers do not strictly enforce this rule. In practice, you can place any element within the <head>
, but the browser will move it to the <body>
. To illustrate this:
<html> <head> <script> customElements.define("in-head", class extends HTMLElement { connectedCallback() { console.log(this.nodeName, "in:", this.parentNode); } }); </script> <in-head></in-head> <title>HELLO!</title> <style> body { background: green; } </style> <script> console.log("End of head"); </script> </head> <body> </body> </html>
In this example, the custom element <in-head>
is placed within the <head>
, but when the page is loaded, the browser moves it to the <body>
. This behavior can be verified by inspecting the document structure using browser developer tools.
For more information, refer to my Dev.to blog post: The head Web Component you never see in F12 Dev tools.