Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Opening-Comment is valid JavaScript?

An old idiom for getting very old browsers to ignore JavaScript blocks in HTML pages is to wrap the contents of the <script> element in HTML comments:

<script>
    <!--
        alert("Your browser supports JavaScript");
    //-->
</script>

The rationale is that old JavaScriptless browsers will render as text the contents of the <script> element, so putting the JavaScript in an HTML comment makes the browser have nothing to render.

A modern browser, on the other hand, will see the <script> element and parse its contents as JavaScript. Consequently, the comments need to be valid JavaScript. The closing HTML comment (-->) is ignored by the JavaScript parser because it is preceded by a JavaScript line-comment (//).

My question is, how does the opening HTML comment (<!--) not cause the JavaScript parser to fail? I have heard from various people that the opening HTML comment is valid JavaScript. If it's true that the opening comment is evaluated as JavaScript, what does it do when it executes?

like image 506
Daniel Avatar asked Oct 27 '12 09:10

Daniel


2 Answers

It seemed to be something exciting, an expression that might have a special meaning (<, ! and -- are all operators in Javascript), but without operands it does not make sense.

Turns out that <!-- is simply equivalent to // in Javascript, it is used to comment out one line.

It is a language feature that does not seem to be well-documented though, and might have been added for the simple reason to support this "hack". And now we have to live with it not to break backwards compatibility.

Needless to say that while this is a funny thing to know, this type of commenting should not be used in real code that other people might happen to read and work with.

The "hack" is also obsolete, because now every browser understands the <script> tag and does not display its contents (even if Javascript is turned off). Personally, in most cases I try avoid writing Javascript directly into HTML anyways and always load my Javascript as an external resource to separate HTML and Javascript.

like image 195
kapa Avatar answered Sep 28 '22 12:09

kapa


In another StackOverflow question, @MathiasBynens gave what I believe is the answer:

Why is the HTML comment open block valid JavaScript?

In short, apparently, this is a non-standard addition to browser-based JS engines that allows these <!-- and --> as single-line comment markers like the // in standard JS.

like image 21
Kyle Simpson Avatar answered Sep 28 '22 11:09

Kyle Simpson