HTML comments in a javascript block?
Actually, only <!--
is valid javascript. To end the html comment in javascript, you actually need to use //-->
.
These days it's not really required to use the HTML comments in Javascript anymore. Browsers which are so old as to not understand the <script>
tag are highly unlikely to be able to render much of anything on a "modern" website, and you should not have to accommodate users who are quite literally on a stone-age browser.
However, if you're intending to include your HTML inside an xml document, and/or are writing x-html, then you'll have to use the xml <![CDATA[
and ]]>
enclosures, as various Javascript operators (&
, <
, and >
in particular) will cause XML parse errors without the enclosures.
This is a previously non-standard feature that browsers and JavaScript engines have always implemented. Nowadays, it cannot be removed from the Web platform, as that would break backwards compatibility. It’s detailed in the JavaScript / Web ECMAScript spec:
<!--
must be treated as the start of aSingleLineComment
— equivalent to//
.var x = true; <!-- x = false; // note: no syntax error x; // true
-->
at the start of a line, optionally preceded by whitespace orMultiLineComment
s, must be treated as aSingleLineComment
— equivalent to//
.var x = true; --> x = false; // note: no syntax error x; // true var x = 1; /* multiline comment! x = 2; */ --> x = 3; x; // 1
Update: This is now upstreamed to the ECMAScript spec. For more background info, see Sunsetting the JavaScript Standard.
No, there is no reason to include them. I regularly omit those comments and have no problems with modern browsers.
<script>
inside strings set via innerHTML
never runs (primarily because it never has in IE and then sites depended on that, so when other browsers reverse-engineered the innerHTML
implementation they had to do that too). The HTML comments there are a red herring.
If you need the <script>
to run, you need to use some other method of inserting the nodes (e.g. createContextualFragment
).