<style> tag within <template>

691 Views Asked by At

I was going through the MDN page for Using Templates and Slots where it mentions while citing an example of using <template> within a Shadow DOM that (emphasis mine):

And because we are appending its contents to a shadow DOM, we can include some styling information inside the template in a element, which is then encapsulated inside the custom element. This wouldn't work if we just appended it to the standard DOM.

My understanding from this statement is that <style> tags within <template> work only in a shadow tree but upon trying an example of doing the same and appending the <template> to the standard DOM, I see that it works (tried in Chrome, Mozilla, and Safari)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <template id="template">
        <style>
            span {
                color: blue;
            }
        </style>
        <span>Span from template</span>
    </template>
</body>
<script>
    const template = document.getElementById('template');
    const templateContent = template.content;
    document.body.appendChild(templateContent);
</script>
</html>

I also thought that it might be referring to appending a standalone <style> tag to the standard DOM for which I tried this snippet which too seemed to work fine

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>Test</div>
</body>
<script>
    const style = document.createElement('style');
    style.innerHTML = `
     div {
         color: blue;
     }
     `;
     document.body.appendChild(style);
</script>
</html>

I'm guessing my inference is incorrect(or are the docs incorrect?). What limitation is that statement actually referring to?

0

There are 0 best solutions below