Why does this Javascript code inside the non-Javascript browser have an additional comment?

In the W3 tutorial, it shows the htis code:

<html> <body> <script type="text/javascript"> <!-- document.getElementById("demo").innerHTML=Date(); //--> </script> </body> </html> 

Then he says:

The two slashes at the end of the comment line (//) are the JavaScript comment character. This prevents JavaScript from executing.

That doesn't make sense to me. I thought all this was commented out.

+3
source share
4 answers

First of all, W3Schools has nothing to do with W3. Their textbooks were pretty terrible before people started complaining, and their confused name implies that they are somehow related to W3, but this is not really the case.

Secondly, this method is no longer needed. There are no browsers available that do not support JS purely ( links , lynx , etc. Do not have problems with JS code at all).

It is assumed that the code should do this:

 <!-- I am a HTML comment --> <!-- If I am placed in a JS block, the web browser should ignore me alert('and me'); --> <!-- If you comment out the HTML comment ending tag, apparently the browser will treat the comment as JS code *only* if the browser supports JS. //--> 
+5
source

In browsers that really understand JavaScript, the open <-- html comment <-- ignored and JS code is executed. The JS // comment in the last line prevents closing --> as JS engine errors. In browsers that don’t understand JavaScript, anything between <-- and --> is treated as an html comment and is ignored.

This whole thing was a precaution for older browsers that did not know about JS. This is not necessary for any modern browser.

If you want to comment out the JS block, enclose the block in /* and */ .

+6
source

If you do it like this, you will get a syntax error:

 <script type="text/javascript"> <!-- document.getElementById("demo").innerHTML=Date(); --> </script> 

JavaScript does not know the closure of HTML comments --> so it needs to be commented out from a script. There is no need to use HTML comments to separate JavaScript, unless you use a simple text editor that colors the code (NoteTab, etc.).

+1
source

All of this is commented out.

In a bowser without Javascript, all <!-- and --> comments will be commented out.

Try to think of it this way: If you tried this code

 <script type="text/javascript"> --> </script> 

then Javascript will throw an error.

+1
source

Source: https://habr.com/ru/post/1401972/


All Articles