Should Javascript still be "hidden" in HTML comment tags?
I have recently inherited some web code and found that all the Jav开发者_JS百科a Script scripts are contained within HTML comment tags
For example:
<script type="text/javascript" language="javascript"><!--
function ValidateForm() { ... }//-->
As I understand it, this method prevented older, non-supported, browsers from interpreting your Java Script. However this is not something I was ever taught to do, and I wonder if this is now considered to be unnecessary, or is this still a common practice? If so, why?
Update: Thanks to kennebec for your advice to leave them in, which I have done for now, and thanks to Emmett also: I'll be sure to leave them out of any future code I write!
http://javascript.crockford.com/script.html:
Do not use the
<!-- //-->
hack with scripts. It was intended to prevent scripts from showing up as text on the first generation browsers Netscape 1 and Mosaic. It has not been necessary for many years.<!-- //-->
is supposed to signal an HTML comment. Comments should be ignored, not compiled and executed. Also, HTML comments are not to include --, so a script that decrements has an HTML error.
It is because of XHTML validator. HTML comments around js code should used outside tag. The validator is supposed to look at your html, not your js.
I strongly recommended this text https://developer.mozilla.org/en/properly_using_css_and_javascript_in_xhtml_documents where is everything about this topic.
My website is XHTML 1.1, which is XML.
My JavaScript is wrapped in
//<![CDATA[
and //]]>
, if there is an XML entity (such as '&', '<', or '>') in the code.
Removing the <!--
could cause a script to fail when there is a </script
as part of the program text inside the <!-- ... -->
.
For example,
<script><!--
function containsScriptEndTag(s) {
return s.indexOf('</script>') >= 0;
}
//-->
</script>
will parse differently without the <!-- ... -->
.
So go ahead and remove them, but check first.
Btw, inside script
elements, they're not called "comments", they're called "escaping text spans".
From http://www.w3.org/TR/2009/WD-html5-20090423/syntax.html#syntax-escape
An escaping text span is a span of text that starts with an escaping text span start that is not itself in an escaping text span, and ends at the next escaping text span end. There cannot be any character references inside an escaping text span — sequences of characters that would look like character references do not have special meaning.
An escaping text span start is a part of text that consists of the four character sequence "
An escaping text span end is a part of text that consists of the three character sequence "-->" (U+002D HYPHEN-MINUS, U+002D HYPHEN-MINUS, U+003E GREATER-THAN SIGN) whose U+003E GREATER-THAN SIGN (>).
An escaping text span start may share its U+002D HYPHEN-MINUS characters with its corresponding escaping text span end.
精彩评论