1. Computing & Technology

Separating JScript and JavaScript

JScript and JavaScript are two similar but different languages. Both are based on ECMAscript and so they do share a lot of their commands in common.

The normal way of combining JavaScript and JScript together involves using feature sensing so that the browsers will run the code from the language that they understand and ignore the code for the language that they don't understand. There is another way we could do it though and that is to provide completely separate scripts for the two languages.

Here's the code for the two script tags that we need to separate JScript and JavaScript so that only the browsers that understand the specific language will run the script. I have placed an alert inline in each of these scripts so that you can see how it works. To use them simply replace the alert with the script in that language that you want to run. You should also move the script to its own file and use a src attribute to supply its filename. I have only placed the code inline so you can see what you need all in the one place.

<script type="text/jscript">
/*@cc_on
  @if (@_jscript)

alert('text/jscript');

  @end
@*/
</script>
<script type="application/javascript">
alert('application/javascript');
</script>

How it Works

Firefox will automatically ignore the first of these script tags completely as it knows that it does not support JScript. Unfortunately Opera, Safari and Google Chrome are not smart enough to realise that they don't understand JScript so they try to run the script anyway. To stop those browsers trying to run a language they don't understand we use the conditional comment feature of the language to wrap the entire content of the JScript so that those browsers that do not understand JScript cannot see the JScript at all.

Internet Explorer will happily run the first of these scripts since it does understand JScript and that conditional comment simply confirms that the browser understands JScript before running its content. IE doesn't understand JavaScript though so it therefore ignores the second of these scripts as it is aware that it doesn't understand JavaScript and so when you specify the JavaScript using the correct MIME type for JavaScript it will be ignored by Internet Explorer.

If it were not for the fact that Opera, Safari, and Chrome are too dumb to know that they do not understand JScript then the conditional comment wrapping the JScript code would be unnecessary.

©2012 About.com. All rights reserved.

A part of The New York Times Company.