1. ホーム
  2. javascript

Why does adding </script> in a comment break the parser? [duplicate]

2023-12-20 09:37:05

Question

Why does adding </script> in a comment break the parser? Is this a bug or is there something in the documentation I've overlooked?

I've tested this in Chrome, Firefox, Opera, Internet Explorer and they all produce the same result.

Single-line comment:

function Foo(){
  // </script>
  alert("bar");
};

Foo();

Multi-line comment:

function Foo(){
  /*
      </script>
  */
  alert("bar");
};

Foo();

How to solved?

This happens because HTML parser as defined by W3C is totally separated from the JavaScript parser. After the <script> tag it looks for the closing </script> , regardless that it's inside comments or strings, because it treats JS code as normal text.