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?
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?
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.
Really old browsers that didn't understand the <script>
tag might assume that it was a formatting tag it didn't understand. They would gracefully fail by rendering the contents of the tag (the script) inline in the page.
By HTML-commenting out the script too those browsers will ignore the content rather than rendering it.
In practice I doubt any of those browsers are still in use and that you can probably get away without the comments nowadays.
It's for some old browsers that were in use last century.
You no longer need them any more today, but using CDATA is considered good practice if you write XHTML.
It's still a problem nowadays if your page gets processed by a sanitation parser that sanitizes by only rewriting the <script>
tag into <xscriptx>
. If you leave in the comment tag, then if the script tag gets sanitized, then at least your javascript will still be hidden from the user by the comment tags. If you leave out the comments, the code will be visible.
An example of a sanitation parser is Google Translate, Google Cache or Proxomitron.