How can JavaScript codes be hidden from old browsers that don't support JavaScript?

How can JavaScript codes be hidden from old browsers that don’t support JavaScript?

I’m aware that this does not answer your question directly, but the truth is that this simply does not need to be done. If a browser does not know how to interpret the JavaScript, almost all browsers will ignore the code anyway. Furthermore, adding the <!-- // --> can be dangerous as well for the following reasons, given by Matt Kruse:

  • Within XHTML documents, the source will actually be hidden from all browsers and rendered useless
  • It is not allowed within HTML comments, so any decrement operations in script are invalid

For a more detailed explanation, I recommend you check out this documentation about the best practices for JavaScript and this question that explains why using HTML comments in JavaScript is bad practice.

If for whatever reason you still want to show content to the user if they have JavaScript disabled (or can’t run it because of an old browser), use a <noscript> tag

If you truly are deadset on commenting out your JavaScript then use this code snippet instead, which shouldn’t give you the error:

//<!--

//-->

Credits: https://stackoverflow.com/questions/31283019/hiding-javascript-from-displaying-in-old-browsers#:~:text=What%20it%20actually%20does%20is,that%20don’t%20support%20JS.