Can a Lit element go in the <head>
tag?
According to the HTML specification, only metadata content is allowed within the <head>
element. If the HTML parser encounters a custom element in the <head>
, it will close the document head at that point and add the rest of the content to the document body.
This means that if you have specific meta tags that need to be present in the <head>
, you cannot replace them with a single custom element.
Instead, you should look for ways to abstract and customize the tags at the HTML templating level.
However, there is an alternative view on this topic.
It is possible to put any element in the <head>
of your document. It will get parsed, but the browser will move the element to the <body>
.
This behavior can be demonstrated with the following code:
<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>
When this code is run, the following output will be displayed in the console:
IN-HEAD in: HEAD End of head
This shows that the <in-head>
element was parsed, but it was moved to the <body>
by the browser.