Why using <!-- and //--> in HTML Javascript? [duplicate] - javascript

This question already has answers here:
Why do I need to comment the <script> tag in HTML?
(4 answers)
Closed 4 years ago.
I'm a beginner of HTML, and I'm learning javascript now.
I read something strange in my book.
I know that <!-- ~~~~ --> is a remark.
But in my book, and in my code, that code did nothing, even not remark.
I want to know why <!-- ~~~~ //-->, not <!-- ~~~~ -->.
And I also want to know why do we use it, and why that code don't do anything.
Thank you in advance.

In the early days of browsers, there were some that didn't even have a javascript engine
they treated <script> as just an unknown tag, but rendered the content anyway
So, to avoid this, one would write inline javascript like
<script><!--
javascript goodness in here
//--></script>
the //--> was so browsers that DID have javascript didn't choke on
-->
which is invalid syntax
// anything here
is a single line comment in javascript
There is absolutely no reason to put such things in code now, however, most (if not all) engines will still not "break" when (the first line of?) inline script contains
<!--

Related

Is it possible to close a div tag right before closing the body tag? [duplicate]

This question already has answers here:
Can jquery add closing element tags (markup) only?
(3 answers)
Closed 7 years ago.
Is it possible to use jQuery (or similar) to add a </div> right before the </body>?
I am working on a large piece of software written in php, hundreds of files. DO not know why, but the author just used a header.php file, while deciding to close the page in each file (</body></html>).
For reasons that I am not going to explain to cut the story short, I cannot edit every single file.
I've added the opening
<div class="container" role="main">
in the header.php file, and I wonder if it is possible to close it before closing the body using javascript so that the resulting html would be:
<body>
<div class="container" role="main">
</div><!-- added via javascript -->
</body>
I've googled and "stackoverflowed" without finding anything.
Thanks for your hints
Sorry, I am neihter able to post comments (I always receive the same error message "Only one additional #user can be notified; the post owner will always be notified"), nor to edit my post. So I am going to write here my answer to all your precious comments first, then I will close my post as duplicate since I believe that the post cited by Jono20201 answers my question... and says NO!!!
I've already tried jQuery .append and .appendTo. But reading the above mentioned thread, which unfortunately did not popped out in my research, I've understood that doing what I want to do is impossibile via javascript (so definitely #Scuzzy is right). So I've two options: 1. using ob_start() and ob_get_contents as suggested by #Jonathan Kuhn; 2. edit each and every file. I think I should go for the second, which is a bit more time consuming but, to me, grants the best result, since the code will be in a good shape (every tag properly closed).The project is a collab one, so I need to be clear
You could try:
$(function() {
$("body").append("</div>");
});
But I worry that different browsers will handling the 'invalid' html differently causing issues.

Enclosing javascript code in comment tags "<!-- //-->" [duplicate]

This question already has answers here:
Should I use HTML comments to capsulate JavaScript code blocks?
(2 answers)
Closed 8 years ago.
Many years ago I developed a habit of enclosing all javascript in files with
<!--
code here
//-->
Not exactly sure why.. other than it's hiding (or not parsing) the code from old browsers, am I right?
Do I need to use it still?
Do I even need anything in my JS pages other than the script code itself? (I'm using Jquery too)
The HTML comment was intended to hide the JavaScript from ancient browsers that didn't understand the <script> element and instead render its contents on the page. HTML comments, ie. <!-- -->, are no longer needed. You can read more about this here

What is <!--> for? [duplicate]

This question already has answers here:
Are HTML comments inside script tags a best practice? [closed]
(10 answers)
Using HTML comment tag <!-- --> still relevant around JavaScript code?
(6 answers)
Closed 9 years ago.
I wonder what this tag in script stands for <!--> //-->
I've noticed it in some usage of javascript, but not always.
Is this necessary or can you just keep it out and what is it's major use?
Before javascript existed, browsers did not know what <script> meant. The tag didn't exist yet. So those browsers would attempt to output the javascript directly! To work around that, we would comment out the javascript with <!-- html comments -->. However, the ending html comment --> is a javascript syntax error, so we have to comment that out with // javascript comments. Nowadays, browsers are smarter and can handle these edge cases.
Those are to create comments in XML and HTML.
<!-- this will not show -->
But this will.
They are included in scripts to hide the code from browsers (technically, this can be a number of different devices, but I'm using "browser" for short) which don't allow for JavaScript.
<script><!--
doSomethingJavaScripty();
// -->
</script>
This means the browser without JavaScript will not accidentally display doSomethingJavaScripty();. It is often paired with a noscript tag (which a browser that supports JS will safely ignore).
This is technically optional. Often times it is a relic of a now-forgotten past, but it is conceivable that it might be useful at some point. It might happen, for example, that you eventually want a service to read and parse your webpage. In such a case, adherence to good practice will prove beneficial. But, even in that circumstance, it has become more common (thankfully) to move to something called "unobtrusive JavaScript."
its used when developers wants to be on safe side, that if browser doesnot support javascript then the code will not be rendered as text, it will become comment

Should I use HTML comments to capsulate JavaScript code blocks?

Some years ago, I was taught that JavaScript code blocks embedded inside HTML should always be capsulated inside HTML comments as following:
<script type="text/javascript">
<!--
var hello = "world";
-->
</script>
I was told to do this, but I never kind of fully figured out why. It kind of seems hacky to use HTML comments, so nowadays I have started using writing my JavaScript code inside the script block without the HTML comments:
<script type="text/javascript">
var hello = "world";
</script>
So my question is: should I use HTML comments to capsulate JavaScript code blocks? Is it safe to just write the script without the comments? I mean am I risking something when I leave out the comment tags?
The HTML comment was intended to hide the JavaScript from ancient browsers that didn't understand the <script> element and instead render its contents on the page. That was way back in the mid-90es, iirc. Nowadays you can safely assume that browsers from that era are no longer present on the web and omit the comments.
Some nice history on that can be found here:
The general rule regarding HTML tags that browsers do not understand is that the browser should ignore the tag completely and treat the content of the page as if that tag were not there. This means that when Netscape 2 first introduced JavaScript (or LiveScript as it was called then), it was necessary to place an HTML comment around the actual script in order to hide the code from other browsers that didn't understand the script tag and which therefore would have displayed the code rather than running it.
The JavaScript language was specifically written to accept the start of an HTML comment as the very first thing in the script and to ignore it in order that the HTML comment could be used to hide the script from people using Netscape 1, Mozaic, Internet Explorer 1, Internet Explorer 2, and other browsers of similar vintage none of which anyone uses any more. It is these prehistoric browsers (in JavaScript terms) that are meant when you see references in antiquated JavaScript tutorials to wrapping your JavaScript inside an HTML comment in order to hide it from "older" browsers.
With Internet Explorer 3, Microsoft introduced their own equivalent to JavaScript which they call JScript. Since then all browsers have at least recognised the script tag and more modern browsers (Netscape 2+, IE3+ etc) the HTML comment is no longer required.So once all your visitors have upgraded to use either Netscape 2, Internet Explorer 3, or a more recent browser than either of those two the commenting out of the script becomes redundant code.
Straight from the source
18.3.2 Hiding script data from user agents
User agents that don't recognize the SCRIPT element will likely render that element's contents as text. Some scripting engines, including those for languages JavaScript, VBScript, and Tcl allow the script statements to be enclosed in an SGML comment. User agents that don't recognize the SCRIPT element will thus ignore the comment while smart scripting engines will understand that the script in comments should be executed.
Another solution to the problem is to keep scripts in external documents and refer to them with the src attribute.
Commenting scripts in JavaScript
The JavaScript engine allows the string "<!--" to occur at the start of a SCRIPT 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>
Furthermore, if you really want to understand what all of this means, read this excellent article. It's lengthy, but worth it.

Are HTML comments inside script tags a best practice? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
The following practice is fairly commonplace in the inline JavaScript I have to work with:
<script type="text/javascript">
<!--
// Code goes here
//-->
</script>
I know that the point is to prevent browsers that are incompatible with JavaScript from rendering the source, but is this still a best practice today? The vast majority of browsers used today can interpret JavaScript; even modern mobile devices usually don't have trouble.
As for the 'why not?' question: I recently had to spend several hours debugging an issue where someone had left off the '//' in front of a '-->' at the end of a script tag buried deep in some pages, and this was causing mysterious JavaScript errors.
What do you do? Is this still considered a 'best practice?'
The important thing is that nowadays, whether a particular browser supports JavaScript or not is irrelevant (clearly the great majority do) - it is irrelevant because almost all understand script blocks, which means that they know to ignore the JavaScript even if they can't interpret it.
Matt Kruse gives a slightly more detailed explanation on his JavaScript Toolbox site for why specifically not to use HTML comments within script blocks.
Quoted from that page:
Don't Use HTML Comments In Script Blocks
In the ancient days of javascript (1995), some browsers like Netscape 1.0 didn't have any support or knowledge of the script tag. So when javascript was first released, a technique was needed to hide the code from older browsers so they wouldn't show it as text in the page. The 'hack' was to use HTML comments within the script block to hide the code.
Using HTML Comments In Script Is Bad
// DON'T do this! Code is just representative on how things were done
<script language="javascript">
<!--
// code here
//-->
</script>
No browsers in common use today are ignorant of the <script> tag, so hiding of javascript source is no longer necessary. In fact, it can be considered harmful for the following reasons:
Within XHTML documents, the source will actually be hidden from all browsers and rendered useless
-- is not allowed within HTML comments, so any decrement operations in script are invalid
I've stopped doing it. At some point you just have to let go of your NCSA Mosaic.
As per W3C Recommendation it was mainly useful to hide the script data from USER AGENTS.
Quoted from the W3c page :
Commenting scripts in JavaScript The JavaScript engine allows the string "<!--" to occur at the start of a SCRIPT 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>
No, it is a hangover from a workaround used when the script element was first introduced. No browser fails to understand the script element today (even if it understands it as "Script that should be ignored because scripting is turned off or unsupported").
In XHTML, they are actively harmful.
I wrote something about the history of it a while back.
Stopped using this a while back. Also, according to Douglas Crockford, you can drop the type attribute from your script tags since the only scripting language available in most browsers is JavaScript.
I would recommend using a CDATA section, as described in this question.
If you are typing manually, I suggest you always use external js files, that would help so much.
Regarding your concern: most browsers are JavaScript safe today. However sometimes people may write simple parsers to fetch a HTML directly - and I must say, the safe quote is really helpful for those clients. Also some non-JS clients like old Lynx would get benefits from this.
If you do not include literal text between script tags- that is, if you load scripts from src files, you can forget about the comments.
I stopped doing that ages ago. You really don't need it in this day and age.
I don't do it but the other day I went to validate my password protected site at w3c. So I had to use their direct input method. It complained about my javascript, so I put the comments back in everything was fine.

Categories