Notification texts go here Contact Us Buy Now!

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

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.

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.