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 in the head, the HTML parser will close the document head from that point and add the rest to the document body. This means that if specific meta tags need to be present in the head, they cannot be replaced with a single custom element.

It is possible to put any element in the <head> of a document, but the browser will move it and all following elements to the <body>. Therefore, it is recommended to look for ways of abstracting and customizing tags at the HTML templating level.

Here's an example that demonstrates what happens when a custom element is placed in the <head>:

<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", document.body.children);
    </script>
</head>

<body>
</body>

</html>

When this code is run, the browser will move the <in-head> element and all following elements to the <body>, and the output in the console will be:

[in-head] in: body

This demonstrates that the custom element was moved to the body, and the console.log statement inside the <script> tag at the end of the head was executed after the custom element was moved.

Note that running the above snippet in a code snippet tool may produce different results, as the tool may add additional elements or modify the HTML structure.

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.