Nested Javascript Templates … is this possible / valid?

You can’t nest script tags. The way script tags work, the browser reads the opening tag and then starts building up a string of the code therein without interpreting that code at all. It stops doing that the first time it sees the exact sequence < / s c r i p t >. The browser will always stop at the first of those it finds, and crucially it ignores any intervening opening tag sequence, like < s c r i p t >. This is because the browser doesn’t parse the script code, that’s not its job. It’s a separation of concerns thing. (script tags probably shouldn’t be tags at all, but rather something more like a CDATA structure. But they’re what we have.)

E.g., from the browser’s point of view:

<script id="Product" type="text/html">              SCRIPT STARTS HERE
    <div class="product">                           SCRIPT CODE CONTINUES
        ....                                        SCRIPT CODE CONTINUES
        <div class="features">                      SCRIPT CODE CONTINUES
            <script id="Features" type="text/html"> SCRIPT CODE CONTINUES (*NOT* START OF SCRIPT)
                <div class="feature">               SCRIPT CODE CONTINUES
                    ...                             SCRIPT CODE CONTINUES
                </div>                              SCRIPT CODE CONTINUES
            </script>                               SCRIPT ENDS
        </div>                                      ENDING `div` TAG (probably mis-matched)
        ...
    </div>
</script>                                           MIS-MATCHED ENDING `script` TAG

Now, if you’re using a server-side templating engine of some kind that will replace those script tags with markup and then send the updated markup to the browser, then it’s up to the templating engine whether it supports nesting. Browsers do not.

Leave a Comment