Notification texts go here Contact Us Buy Now!

Can a Lit element go in the <head> tag?

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.

However, it's important to note that you can still put any element in the <head> of your document, but the browser will move it and all following elements to the <body>.

So, you can use a Web Component in the <head>, but you need to put it at the end of the <head>, and the Web Component can then create elements in the <head>.

Valid HEAD elements are: meta, link, title, style, script, noscript, base.

<html>

<head>
    <script>
        customElements.define("in-head", class extends HTMLElement {
            connectedCallback() {
                console.log(this.nodeName, "in:", this.parentNode);
                document.head.append(Object.assign(document.createElement("style"), {
                    textContent: "body {background:green}",
                    onload: (e) => console.log("style in", e.target.parentNode)
                }));
            }
        });
    </script>
    <in-head></in-head>
    <script>
        console.log("End of head", document.body.children);
    </script>
</head>

<body>
</body>

</html>

Note: running the above snippet outputs a different result than running it in the browser, because SOsnippet adds an additional <script> tag.

You can find more information on Web Components in the <head> in my Dev.to blog-post The head Web Component you never see in F12 Dev tools.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.