Are HTML Comments Inside Script Tags a Best Practice

Are HTML comments inside script tags 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

Why do I need to comment the script tag in HTML?

It's not really necessary any more. This has only ever served as a backwards-compatibility hack of sorts - when scripts first started being inserted into static HTML pages, most browsers couldn't support them. Without the comments, they would ignore the semantics of the <script> tag (which they didn't understand), and then would emit the script source onto the page.

Ironically, the solution was a hack in itself - AFAIK, no part of the HTML spec says that script tags should be parsed when inside of comments. The fact that all browsers picked this up seems to be more of a coincidence than anything else. Certainly with XHTML, comments are comments so a fully conformant browser would have to ignore your scripts.

So basically, unless you want to support really, really old browsers (at the cost of breaking some new ones) it's no longer necessary to do this.

Why would a script tag contains HTML comments in it?

In ancient times some browsers didn’t understand the <script> tag so it was made in a way that you can add comments to the beginning without issues. This causes anything inside to not be shown on the page if the browser doesn’t know what to do with the tag.

This hasn’t been needed in a very long time so it’s safe to remove them.

Why does adding /script in a comment break the parser?

This happens because HTML parser as defined by W3C is totally separated from the JavaScript parser. After the <script> tag it looks for the closing </script>, regardless that it's inside comments or strings, because it treats JS code as normal text.

Does it still make sense to use HTML comments on blocks of JavaScript?

No, absolutely not. Any user agent, search engine spider, or absolutely anything else these days is smart enough to ignore Javascript if it can't execute it.

There was only a very brief period when this was at all helpful, and it was around 1996.

Where should I put script tags in HTML markup?

Here's what happens when a browser loads a website with a <script> tag on it:

  1. Fetch the HTML page (e.g. index.html)
  2. Begin parsing the HTML
  3. The parser encounters a <script> tag referencing an external script file.
  4. The browser requests the script file. Meanwhile, the parser blocks and stops parsing the other HTML on your page.
  5. After some time the script is downloaded and subsequently executed.
  6. The parser continues parsing the rest of the HTML document.

Step #4 causes a bad user experience. Your website basically stops loading until you've downloaded all scripts. If there's one thing that users hate it's waiting for a website to load.

Why does this even happen?

Any script can insert its own HTML via document.write() or other DOM manipulations. This implies that the parser has to wait until the script has been downloaded and executed before it can safely parse the rest of the document. After all, the script could have inserted its own HTML in the document.

However, most JavaScript developers no longer manipulate the DOM while the document is loading. Instead, they wait until the document has been loaded before modifying it. For example:

<!-- index.html -->
<html>
<head>
<title>My Page</title>
<script src="my-script.js"></script>
</head>
<body>
<div id="user-greeting">Welcome back, user</div>
</body>
</html>

JavaScript:

// my-script.js
document.addEventListener("DOMContentLoaded", function() {
// this function runs when the DOM is ready, i.e. when the document has been parsed
document.getElementById("user-greeting").textContent = "Welcome back, Bart";
});

Because your browser does not know my-script.js isn't going to modify the document until it has been downloaded and executed, the parser stops parsing.

Antiquated recommendation

The old approach to solving this problem was to put <script> tags at the bottom of your <body>, because this ensures the parser isn't blocked until the very end.

This approach has its own problem: the browser cannot start downloading the scripts until the entire document is parsed. For larger websites with large scripts and stylesheets, being able to download the script as soon as possible is very important for performance. If your website doesn't load within 2 seconds, people will go to another website.

In an optimal solution, the browser would start downloading your scripts as soon as possible, while at the same time parsing the rest of your document.

The modern approach

Today, browsers support the async and defer attributes on scripts. These attributes tell the browser it's safe to continue parsing while the scripts are being downloaded.

async

<script src="path/to/script1.js" async></script>
<script src="path/to/script2.js" async></script>

Scripts with the async attribute are executed asynchronously. This means the script is executed as soon as it's downloaded, without blocking the browser in the meantime.
This implies that it's possible that script 2 is downloaded and executed before script 1.

According to http://caniuse.com/#feat=script-async, 97.78% of all browsers support this.

defer

<script src="path/to/script1.js" defer></script>
<script src="path/to/script2.js" defer></script>

Scripts with the defer attribute are executed in order (i.e. first script 1, then script 2). This also does not block the browser.

Unlike async scripts, defer scripts are only executed after the entire document has been loaded.

According to http://caniuse.com/#feat=script-defer, 97.79% of all browsers support this. 98.06% support it at least partially.

An important note on browser compatibility: in some circumstances, Internet Explorer 9 and earlier may execute deferred scripts out of order. If you need to support those browsers, please read this first!

(To learn more and see some really helpful visual representations of the differences between async, defer and normal scripts check the first two links at the references section of this answer)

Conclusion

The current state-of-the-art is to put scripts in the <head> tag and use the async or defer attributes. This allows your scripts to be downloaded ASAP without blocking your browser.

The good thing is that your website should still load correctly on the 2% of browsers that do not support these attributes while speeding up the other 98%.

References

  • async vs defer attributes
  • Efficiently load JavaScript with defer and async
  • Remove Render-Blocking JavaScript
  • Async, Defer, Modules: A Visual Cheatsheet

Using comments in script link tag

Maybe your coworker is concerned you'll get in the habit of doing this

<script src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js" type="text/javascript">
// import jQuery
// cdn refers to a remotely hosted library
</script>

And then eventually struggle to figure out why this doesn't work

<script src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js" type="text/javascript">
$(document).ready(function() {
$('#ActionButton').click(DoAction);
});
</script>

Because you've developed a bad habit

Is it bad practice to embed JavaScript into the body of HTML?

It's perfectly valid.

You wouldn't want to put great big blocks of code mixed up in the markup there (better to use external scripts), but it can be useful to:

  • add extra binding information for progressive-enhancement (where that data is difficult to fit into a classname or other approach to hiding extended information in attributes); or

  • where it's necessary to kick off a scripted enhancement as quickly as possible (rather than waiting for window-load/document-ready). An example of this would be autofocus, which can irritate if fired too late.

You may be thinking of <style> elements, which aren't allowed in <body> (although most browsers allow it nonetheless).



Related Topics



Leave a reply



Submit