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?'
JavaScript comments can be used to explain JavaScript code, and to make it more readable. JavaScript comments can also be used to prevent execution, when testing alternative code.
What are the negatives of HTML comments? worsens the UX - even not visible, the HTML comments are part of the DOM tree and increase the number of DOM elements. This, in turn, affects the quickness and responsiveness, also leads to slower CSS selectors and DOM manipulation.
An HTML comment begins with <! –– and the comment closes with ––> . HTML comments are visible to anyone that views the page source code, but are not rendered when the HTML document is rendered by a browser.
That's because SCRIPT TAG is not a VOID ELEMENT. In an HTML Document - VOID ELEMENTS do not need a "closing tag" at all!
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:
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:
I've stopped doing it. At some point you just have to let go of your NCSA Mosaic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With