What does it mean! - // - in javascript?

3

I ran into an issue where a tag <script> was displayed and contained these HTML comment characters.

Function example

<html>
  <head>
<script type="text/javascript">
<!--
  function Alert(){
  alert("apenas uma função exemplo")
  }
//-->
</script>
    </head>
  <body>
    <button onClick="Alert()">Funcão Exemplo</button>
    </body>
      </html>

If you put this structure in an ASP.NET WebForms application, and simply remove the tag comment from the end of the script , it does not work.

<html>
  <head>
<script type="text/javascript">
<!--
  function Alert(){
  alert("apenas uma função exemplo")
  }
 
</script>
    </head>
  <body>
    <button onClick="Alert()">Funcão Exemplo</button>
    </body>
      </html>
    
asked by anonymous 21.06.2016 / 15:16

3 answers

7

This is an tag of HTML comment. It starts with !-- and ends with -- . Without this comment the parser of the HTML will be lost.

It is common to use it to "hide" a script JavaScript. Except this will complicate with this -- of HTML. Then use // which is the comment of JavaScript to ignore this code that is in the background of HTML.

You notice that it looks like one thing but at bottom are two different constructions, and more, of different languages?

If you do not have this you will consider that the comment has not been completed and everything else will be disregarded as a useful HTML code.

This is a great reason not to use this kind of thing. In fact, this is much less used nowadays. The general recommendation is to not have JavaScript code inside HTML. Create an external file and include it by traditional means. It gets more organized, has several advantages besides avoiding this confusion.

This is independent of the technology you are using on the server.

    
21.06.2016 / 15:22
2

Used for Javascript, it's just a consensus of end-of-function guidance. Like for example comments to mark start and end of a given code boundary, I myself use it to identify myself.

Look if this helps.

function teste(){
   alert('sou um robô');  
}
// **>
<div><!-- div do conteudo x -->
 <p>yyyyyyyyyy</p> 
</div> <!-- fim do conteudo da div x -->
    
21.06.2016 / 15:32
2

This is an HTML code comment. As far as I know this has been used in the past, to make browsers that did not have Javascript support have no problems with this "new tag" <script> .

    
21.06.2016 / 21:55