Should I use HTML comments to capsulate JavaScript code blocks? - javascript

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.

Related

Is placing javascript directly on HTML document deprecated?

I am shocked to read the following from Quirksmode:
Deprecated: Direct JavaScripts
Do not use direct JavaScripts for the reasons explained in section 2C
of the book. This section is only maintained for historical reasons.
The simplest method is to place your scripts directly in the page. How
to place
<script language="javascript" type="text/javascript">
<!--
script goes here
// -->
</script>
Based on my understanding reading the article, javascripts are to be included using the src attribute on <script> tags instead. I don't have the book and can't find further references online that says this. Does anyone know whether this is correct or did I misinterpret what it is trying to say?
No HTML specification marks inline JavaScript as deprecated or obsolete.
It is widely regarded as being less than best practise though.
PPK means that the section itself is deprecated. The advice presented there was generally accepted and relevant at the time of publication, but it no longer aligns with current markup languages and best practices:
The language attribute has been deprecated since HTML 4.01.
In HTML5, the default value of the type attribute is text/javascript—thus, it can often be discarded.
The HTML comments (<!-- and -->) surrounding the script itself are a workaround for the IE 2 and Netscape 1 generation of browsers, and have not been required for nearly 20 years.
Later he advises that you place scripts in the head of your document. This made sense in the days of dial-up, but nowadays it is recommended that outside of a few specific circumstances (e.g. Modernizr, html5shiv) you should place scripts at the end of your document body to prevent them from blocking rendering and parallel downloads.
More current advice
Avoid inlining scripts in general for better maintainability and cacheability. You are still allowed to inline scripts, and it may make sense if:
the script is dynamically generated for just that page; or
the script is very small, and you can demonstrate a measurable and worthwhile improvement in performance due to avoiding the additional HTTP request.
Unless otherwise necessary, use the following syntax for inline JS.
HTML5:
<script>
// ...
</script>
HTML 4.01:
<script type="text/javascript">
// ...
</script>
XHTML5:
<script>
//<![CDATA[
// ...
//]]>
</script>
XHTML 1.x:
<script type="text/javascript">
//<![CDATA[
// ...
//]]>
</script>
It is not deprecated, and it is still used widely.
If you look at this question: https://softwareengineering.stackexchange.com/questions/86589/why-should-i-avoid-inline-scripting it is very well explained why its a bad idea.
The biggest problem i have with it, is that it makes your html pages look stuffed. If you for example have a bit of javascript inline, and a bit of javascript in another file, it is pretty hard to find the right code if you need to change it.
Same goes for inline css. It makes your html files harder to read and understand.
script tag is not deprecated.
The relevant section is called "Deprecated: Direct JavaScripts", and
the note referes to the section's title. Must read:
"Do not use "Direct JavaScripts" recommendations for tag
syntax. This section is only maintained for historical reasons."
the section is deprecated
http://www.peachpit.com/articles/article.aspx?p=1338952&seqNum=3

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

Most common use cases for the HTML5 shiv/shim JS script

I often see people suggesting I include the HTML5 shiv JS script to make HTML5 work in Internet Explorer but I can't find a clear explanation for the most common use cases this will cover.
Might someone give common scenarios of why one would need this JS script?
Also, does it need to be in the <head> or can I put it with the rest of my JS at the bottom of the <body> tag such that it doesn't block the UI thread?
Internet Explorer prior to version 9 refuses to apply any CSS styling to HTML elements it does not recognise, this includes the new elements brought in by HTML5. By creating the elements through the JavaScript DOM it suddenly and magically realises that the elements should indeed be styled.
You can write a naive and simple script that loops over an array of HTML5 tag names you want calling document.createElement(tagName). This may work for you in most cases, however, printing HTML5 pages in IE and adding HTML5 content through innerHTML will cause you further problems at which point it would be an idea to switch to the shiv.
HTML5 shiv can, to my best knowledge, be placed in the head or after the body tag if you prefer. I would recommend using conditional comments so that only IE loads it.

Using JS to write a noscript tag

Is there any practical reason why you would write out a <noscript> tag with JavaScript's document.write()? Our ad department has been doing this for years and still does it after I've pointed it out. I'm 99% certain that this is due to an ancient ad template written by someone who didn't know what he was doing and no one has thought to change it because, "why fix what ain't broke?" Or maybe someone is reading their "best practices" wrong ("Always include a alternative for browsers that have JS disabled"). Or maybe there's a really good reason I don't know about.
The only conceivable thing I can think of is that you could use it to modify the DOM without it appearing visible on the page and maybe use that content like a template for later use, but this seems pretty far-fetched.
(edit)
The tag in this case contains a standard <img src="/path/to/image" />. Because this is what the original, non-dynamic ad tag would have looked like, this makes me think this is just copy-pasted garbage.
The other thing I should say is that the reason I'm not 100% sure this is an oversite is because of the recent pattern of putting html templates inside <script type="text/x-my-custom-template">...</script>. I'm sceptical that someone on our end would have come up with this on their own, but it could have been a standard ad practice by someone with unusual cleverness.
Is there any practical reason why you would write out a <noscript> tag with JavaScript's document.write()
Nope. The two (<script> and <noscript>) are mutually exclusive. It's like writing a piece of code like this:
if (true && false) {
// do something important
}
If JavaScript is enabled, the browser ignores the <noscript> tag. On the other hand, if JavaScript is disabled, the <noscript> tag will never be written, because the <script> tag is ignored.
This is used for bot detection / fingerprinting.
For example if I use
document.write('<script src='...'>...</script><noscript><img>....</noscript>');
Chrome 55+ blocks not same origin scripts written from document.write(). This means the above <noscript> actually will run on certain/newer versions of chrome despite coming from a "script".
The assumed purpose is if the bot is pretending to be for example (via spoofing its user agent) a specific version of chrome, and the script is not blocked, it would point to the fact that its not really chrome (bot).
You can add child node in a specific html tags.
var noscript = document.createElement('noscript')
var iframe = document.createElement('iframe')
iframe.setAttribute('src', "<your source>")
iframe.setAttribute("height", "0")
iframe.setAttribute("width", "0")
iframe.setAttribute("style", "display:none;visibility:hidden")
noscript.appendChild(iframe)
document.body.appendChild(noscript)

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