Using HTML Comment Tag <!-- --> Still Relevant Around JavaScript Code

Using HTML comment tag !-- -- still relevant around JavaScript code?

HTML comments, ie. <!-- -->, are no longer needed. They were intended to allow browsers that didn't understand the <script> tag to degrade gracefully. These browsers, eg. Netscape 1.x are no longer found in the wild. So there is really no point in putting HTML comments in your script tags anymore.

If you want your HTML to validate as XHTML or XML, you probably want to use a commented out CDATA tag.


<script type="text/javascript">
//<![CDATA[
document.write("Hello World!");
//]]>
</script>

The reason for this is so your <, >, &, " and ' that are part of your javascript code won't have to be encoded as <, >, &, " and ' respectively.

Does HTML comment !-- act as a single-line comment in JavaScript, and why?

From testing it seems that JavaSript treats <!-- like // a one-liner

Yes it does, as specified in the ES6 spec, annex B:

B.1.3 HTML-like Comments

Comment ::
MultiLineComment
SingleLineComment
SingleLineHTMLOpenComment
SingleLineHTMLCloseComment
SingleLineDelimitedComment

SingleLineHTMLOpenComment ::
<!-- SingleLineCommentCharsopt

However, note the description of annex B:

This annex describes various legacy features and other characteristics of web browser based ECMAScript implementations. All of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification. However, the usage of these features by large numbers of existing web pages means that web browsers must continue to support them. The specifications in this annex defined the requirements for interoperable implementations of these legacy features.

These features are not considered part of the core ECMAScript language. Programmers should not use or assume the existence of these features and behaviours when writing new ECMAScript code. ECMAScript implementations are discouraged from implementing these features unless the implementation is part of a web browser or is required to run the same legacy ECMAScript code that web browsers encounter.

So, this part only exists to describe existing "unofficial" behavior and as soon as browsers stop implementing this behavior, will be removed from the spec.

Are HTML comments inside script tags a best practice?

The important thing is that nowadays, whether a particular browser supports JavaScript or not is irrelevant (clearly the great majority do) - it is irrelevant because almost all understand script blocks, which means that they know to ignore the JavaScript even if they can't interpret it.

Matt Kruse gives a slightly more detailed explanation on his JavaScript Toolbox site for why specifically not to use HTML comments within script blocks.

Quoted from that page:


Don't Use HTML Comments In Script Blocks


In the ancient days of javascript (1995), some browsers like Netscape 1.0 didn't have any support or knowledge of the script tag. So when javascript was first released, a technique was needed to hide the code from older browsers so they wouldn't show it as text in the page. The 'hack' was to use HTML comments within the script block to hide the code.

Using HTML Comments In Script Is Bad

// DON'T do this! Code is just representative on how things were done
<script language="javascript">
<!--
// code here
//-->
</script>


No browsers in common use today are ignorant of the <script> tag, so hiding of javascript source is no longer necessary. In fact, it can be considered harmful for the following reasons:

  • Within XHTML documents, the source will actually be hidden from all browsers and rendered useless
  • -- is not allowed within HTML comments, so any decrement operations in script are invalid

How do I get an HTML comment with javascript

Using a NodeIterator (IE >= 9)

The best method is to use a dedicated NodeIterator instance iterating all comments contained in a given root element.

See it in action!

function filterNone() {
return NodeFilter.FILTER_ACCEPT;
}

function getAllComments(rootElem) {
var comments = [];
// Fourth argument, which is actually obsolete according to the DOM4 standard, is required in IE 11
var iterator = document.createNodeIterator(rootElem, NodeFilter.SHOW_COMMENT, filterNone, false);
var curNode;
while (curNode = iterator.nextNode()) {
comments.push(curNode.nodeValue);
}
return comments;
}

window.addEventListener("load", function() {
console.log(getAllComments(document.body));
});

Using a custom-made DOM traversal (to support IE < 9 as well)

If you have to support older browsers (e.g. IE <9), you need to traverse the DOM yourself and extract those elements whose node type is Node.COMMENT_NODE.

See it in action!

// Thanks to Yoshi for the hint!
// Polyfill for IE < 9
if (!Node) {
var Node = {};
}
if (!Node.COMMENT_NODE) {
// numeric value according to the DOM spec
Node.COMMENT_NODE = 8;
}

function getComments(elem) {
var children = elem.childNodes;
var comments = [];

for (var i=0, len=children.length; i<len; i++) {
if (children[i].nodeType == Node.COMMENT_NODE) {
comments.push(children[i]);
}
}
return comments;
}

Extracting a node's contents and delete it

Independent of the way you choose from above, you receive the same node DOM objects.

Accessing a comment's contents is as easy as commentObject.nodeValue.

Deleting a comment is a bit more verbose: commentObject.parentNode.removeChild(commentObject)

Valid comment in Javascript

That is an HTML comment and the use of this format in script harks back to the '90s where some browsers did not understand JavaScript so we have to HIDE the JS from those browsers

Typically

<script type="text/javascript"><!-- // hide from older browsers
document.write("Yes we have no bananas"); // this will be written if the browser understands JS
// --></script>

Should I use HTML comments to capsulate JavaScript code blocks?

The HTML comment was intended to hide the JavaScript from ancient browsers that didn't understand the <script> element and instead render its contents on the page. That was way back in the mid-90es, iirc. Nowadays you can safely assume that browsers from that era are no longer present on the web and omit the comments.

Some nice history on that can be found here:

The general rule regarding HTML tags that browsers do not understand is that the browser should ignore the tag completely and treat the content of the page as if that tag were not there. This means that when Netscape 2 first introduced JavaScript (or LiveScript as it was called then), it was necessary to place an HTML comment around the actual script in order to hide the code from other browsers that didn't understand the script tag and which therefore would have displayed the code rather than running it.

The JavaScript language was specifically written to accept the start of an HTML comment as the very first thing in the script and to ignore it in order that the HTML comment could be used to hide the script from people using Netscape 1, Mozaic, Internet Explorer 1, Internet Explorer 2, and other browsers of similar vintage none of which anyone uses any more. It is these prehistoric browsers (in JavaScript terms) that are meant when you see references in antiquated JavaScript tutorials to wrapping your JavaScript inside an HTML comment in order to hide it from "older" browsers.

With Internet Explorer 3, Microsoft introduced their own equivalent to JavaScript which they call JScript. Since then all browsers have at least recognised the script tag and more modern browsers (Netscape 2+, IE3+ etc) the HTML comment is no longer required.So once all your visitors have upgraded to use either Netscape 2, Internet Explorer 3, or a more recent browser than either of those two the commenting out of the script becomes redundant code.

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.

Visual studio code comment in HTML files

Finally i found what the problem was. I had installed the twig plugin (for the Twig php template engine) and that was causing the comments issue.

Are nested HTML comments possible?

When you nest a comment, replace "--" with "- -". When you un-nest, reverse the procedure. It's not the <!-- that is forbidden but the --.

Example:

<!-- some stuff
<!- - some inner stuff - ->
<!- - a sibling - ->
the footer -->


Related Topics



Leave a reply



Submit