Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Commenting out <script> closing tag. Syntax OK or not?

i see this every once in a while when working on projects where customers provide code:

<script src="xx" type="xx">//</script>

And i always wondered if that's in any way a correct syntax.
It doesn't bother any browser at least. But it messes up the syntax highlighter of my editor very badly as it's not recognizing the closing tag when commented out.

Another flavour would be:

<script>
  //some code
//</script>

I only know this one for preventing code leak into the page:

<script>
 //<!--
 //some code
 //-->
</script>

And i absolutely don't know what the other ones want to prevent.

like image 237
bardiir Avatar asked Dec 08 '25 12:12

bardiir


2 Answers

It is formally correct syntax to write <script src="xx" type="xx">//</script>, because the HTML document is parsed, treating // just as data, and this data is then discarded, since the element has a src attribute. It would of course conform to JavaScript syntax, too, constituting an empty program, with an empty comment.

The // serves no useful purpose, though. It is debatable whether a nonempty comment would be useful; the HTML5 drafts suggest that it could, see Inline documentation for external scripts there.

Using //</script> is formally correct but useless.

A syntax highlighter that gets messed up with it has a bug (it has not been programmed to parse script elements properly).

Constructs like the one you mention for “preventing code leak into the page”, with <!-- and --> inside script code, are worse than useless codelore. They are useless, since nobody uses Netscape 1 any more. They are worse than useless, since people make typing mistakes in trying to use them (and since by XHTML rules, the comment-like construct is a comment and may be removed by a browser). Besides, the specific construct you mention would not even do the trick on Netscape 1; it would make the characters “//” appear in page content.

like image 128
Jukka K. Korpela Avatar answered Dec 10 '25 02:12

Jukka K. Korpela


This is still a valid javascript line. It is a blank comment.

//</script>

So browsers won't have any trouble with it. If your syntax highlighter doesn't recognize it, that is a fault with the syntax highlighter.

Yes, I do agree it would be much easier to read if the code didn't have a blank comment at the end.

like image 38
nunespascal Avatar answered Dec 10 '25 02:12

nunespascal