I’d like to make an SEO lit component where I can pass data to fill in meta tags, etc so I don’t need to repeat them on every index page. If I place my component like so…
<head>
<script type="module" src="/src/lit-head.ts"></script>
<lit-head></lit-head>
</head>
It still places the rendered markup that’s returned by the lit-head
module inside the body…
Anyway to get this to work? It would also make it possible to localize things like my meta tags, title, description, etc.
2
Answers
The HTML spec only allows metadata content within the
<head>
element.If the HTML parser sees a custom element there, it’ll close the document head from that point and the rest will be added to the document body. So if you need specific meta tags to be present in the head, you cannot replace those with a single custom element.
You should look for ways of abstracting and customizing the tags at the HTML templating level.
Yes, you can put any element in the
<head>
of your document.It will get parsed, but the Browser will move it and all following elements to the
<body>
So put/use your
<in-head>
Web Component at the end of the headYour Web Component than can create Elements in the
<head>
Valid HEAD elements are: meta, link, title, style, script, noscript, base
Note: running above snippet outputs a different result than running in the browser, because SOsnippet adds an additional
<script>
tagSee my Dev.to blog-post The head Web Component you never see in F12 Dev tools how I use a Web Component in the
<head>