Notification texts go here Contact Us Buy Now!

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

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.

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.