Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to comment the <script> tag in HTML?

Most examples I've seen have scripts in a html page being enclosed by

<!--
...
-->

I've tried writing it without the comment tags and there doesn't seem to be any difference. Why is the comment tag used and what function does it serve?

like image 921
jon2512chua Avatar asked Dec 12 '10 12:12

jon2512chua


People also ask

How do you comment a script tag in HTML?

Single line comments start with // . Any text between // and the end of the line will be ignored by JavaScript (will not be executed).

What is the importance of script tag in HTML?

The <script> HTML element is used to embed executable code or data; this is typically used to embed or refer to JavaScript code. The <script> element can also be used with other languages, such as WebGL's GLSL shader programming language and JSON.

What are comments in JavaScript?

The JavaScript comments are meaningful way to deliver message. It is used to add information about the code, warnings or suggestions so that end user can easily interpret the code. The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the browser.


1 Answers

It's not really necessary any more. This has only ever served as a backwards-compatibility hack of sorts - when scripts first started being inserted into static HTML pages, most browsers couldn't support them. Without the comments, they would ignore the semantics of the <script> tag (which they didn't understand), and then would emit the script source onto the page.

Ironically, the solution was a hack in itself - AFAIK, no part of the HTML spec says that script tags should be parsed when inside of comments. The fact that all browsers picked this up seems to be more of a coincidence than anything else. Certainly with XHTML, comments are comments so a fully conformant browser would have to ignore your scripts.

So basically, unless you want to support really, really old browsers (at the cost of breaking some new ones) it's no longer necessary to do this.

like image 65
Andrzej Doyle Avatar answered Oct 05 '22 23:10

Andrzej Doyle