Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does <!-- Not Throw a Syntax Error?

I noticed in some legacy code the following pattern:

<script>
    <!--
    // code
    // -->
</script>

After some research, this appears to be a very old technique for hiding the contents of script elements from the DOM when the browser did not support the <script> element. More information can be found here.

My concern is this: why does <!-- not throw a Syntax Error? I've found on whatwg.org's website that <!-- should be functionally equivalent to //, and it links off to a snippet from the ECMAScript grammar about comments. The problem is, <!-- isn't defined by that grammar at all.

So this seems like undefined behavior that happens to be implemented by all major browsers. Is there a specification that allows for this, or is this a backwards-compatibility hack that people are bringing forward?

like image 529
raynjamin Avatar asked Oct 15 '14 21:10

raynjamin


2 Answers

Officially: Because there's specific handling for it in the HTML spec. E.g., it's a "by fait" thing. It's not a JavaScript thing, you won't find it in the JavaScript grammar.

Unofficially, it would appear that at least some JavaScript engines handle it intrinsically, sometimes in ways that make what I believe is valid JavaScript invalid. For instance, on V8 in a browser, this fails:

eval("var a = 1; var n = 3; console.log(a<!--n);")

...with Unexpected end of input. I'm pretty sure it shouldn't, but I'm not a parsing lawyer. I'd expect it to log false to the console, like this does:

eval("var a = 1; var n = 3; console.log(a<! --n);")
// Note the space -------------------------^

Side note: Meteor's jsparser agrees with me, copy and paste just the bit inside the double quotes into it.

Note that the characters <! do not appear in the specification, nor does there appear to be anything near any of the 70 occurrences of the word "comment" in there, nor is it anywhere in the comment grammar, so it wouldn't seem to be an explicit in-spec exception. It's just something at least some JavaScript engines do to avoid getting messed up by people doing silly things. No great surprise. :-)

like image 89
T.J. Crowder Avatar answered Oct 18 '22 21:10

T.J. Crowder


It is defined by the W3's docs for the user agents:

The JavaScript engine allows the string "<!--" to occur at the start of a SCRIPT element, and ignores further characters until the end of the line.

So browsers follow these standards

like image 23
LcSalazar Avatar answered Oct 18 '22 22:10

LcSalazar