Using HTML comment tag <!-- --> still relevant around JavaScript code?

Viewed 41371

Is it still relevant to use HTML comment tag around JavaScript code?

I mean

<html>
    <body>
        <script type="text/javascript">
            //<!--
            document.write("Hello World!");
            //-->
        </script>
    </body>
</html>
6 Answers

Even in modern browsers, it can be useful. I actually ran into this problem today, precisely because I wanted to avoid having javascript embedded in my html.

I have an html page that is served up on http://host/variable_app_name/pagename, where variable_app_name can have many values (y'know, variable). If it wants to access static files it has to use a url like http://host/static/variable_app_name/filename, so I cannot specify the static file location without first looking at browser's location to find the value of variable_app_name.

To link to the main javascript file I do the following:

<script type="text/javascript" >
   var variable_app_name = window.location.pathname.split('/')[1];
   document.write('<script type="text/javascript" src="/static/'+variable_app_name+'/pagename.js"></script>\n');
</script>

The above code will explode even in the latest version of Chrome, because the script tag will be terminated in the middle of a javascript string and the remainder of the string will be interpreted as html, like so:

<script type="text/javascript" >
   var variable_app_name = window.location.pathname.split('/')[1];
   document.write('<script type="text/javascript" src="/static/'+variable_app_name+'/pagename.js">
</script>
\n');
</script>

There are many ways to fix this, but I like to use an html comment.

With html comment:

<script type="text/javascript" >
<!--
   var variable_app_name = window.location.pathname.split('/')[1];
   document.write('<script type="text/javascript" src="/static/'+variable_app_name+'/pagename.js"></script>\n');
-->
</script>

Breaking up the javascript string:

<script type="text/javascript" >
   var variable_app_name = window.location.pathname.split('/')[1];
   document.write('<script type="text/javascript" src="/static/'+variable_app_name+'/pagename.js"></scr'+'ipt>\n');
</script>

Create and append the script tag rather than using document.write:

<script type="text/javascript" >
   var variable_app_name = window.location.pathname.split('/')[1];
   var script = document.createElement('script');
   script.type = 'text/javascript';
   script.src = '/static/'+variable_app_name+'/pagename.js';
   document.head.appendChild(script);
</script>

I like to use the html comment because it's a concise change and it won't need replicating or thinking about for each linked file.

if your looking to comment out js include lines or a complete js block of code, just rename the tag name like below:

Example before:

<script src="js/notification.js"></script>

Example After:

<script__ src="js/notification.js"></script__>
Related