I just tried this code on my browser (Chrome 39, Windows 8) :-
<html>
<body>
<script>
<!--
document.write("<h1>Hello</h1>");
-->
</script>
</body>
</html>
This produces the Header text on the browser. But when I make a slight change- put the HTML comment stuff on a single line,
<html>
<body>
<script>
<!-- document.write("<h1>Hello</h1>"); -->
</script>
</body>
</html>
This doesn't display anything. Why is it so? I don't think HTML comments are in the Javascript standards.
p.s. I know how to put javascript comments. I'm only wondering about this erratic behavior.
That's the way to hide javascript to browsers that don't recognize the script
element. The first line is allways ignored: Hiding script data from user agents
Commenting scripts in JavaScript
The JavaScript engine allows the string
"<!--"
to occur at the start of aSCRIPT
element, and ignores further characters until the end of the line. JavaScript interprets"//"
as starting a comment extending to the end of the current line. This is needed to hide the string"-->"
from the JavaScript parser.<SCRIPT type="text/javascript"> <!-- to hide script contents from old browsers function square(i) { document.write("The call passed ", i ," to the function.","<BR>") return i * i } document.write("The function returned ",square(5),".") // end hiding contents from old browsers --> </SCRIPT>
来源:https://stackoverflow.com/questions/27428277/why-does-javascript-ignore-single-line-html-comments